Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. The Lounge
  3. How would you code it?

How would you code it?

Scheduled Pinned Locked Moved The Lounge
csharpcsshelpquestion
59 Posts 15 Posters 1 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • P Pete OHanlon

    What happens when it becomes hello + " " + value + " " + value2 + value + " " + item.Format("{0:D}") + hello;? Is that still easy to visualize and have you looked at the IL that this produces?

    Deja View - the feeling that you've seen this post before.

    P Offline
    P Offline
    PIEBALDconsult
    wrote on last edited by
    #36

    Or if you need to include a value multiple times? One that is costly to retrieve? With Option2, at best you declare a temporary value for it; but using Option1 doesn't require that. Or if you want to include a value in more than one format, like printing an int in both decimal and hexadecimal.

    1 Reply Last reply
    0
    • A Al Beback

      Pete O`Hanlon wrote:

      What happens when it becomes hello + " " + value + " " + value2 + value + " " + item.Format("{0:D}") + hello;?

      I prefer it to string.Format("{0} {1} {2}{1} {3:D}{0}", hello, value, value2, item); Although it does appear neater, I can't visualize anything here. All I see is 6 placeholders and 4 variables. Bringing it all together mentally is, to me, more difficult.

      Pete O`Hanlon wrote:

      you looked at the IL that this produces

      That's the best part. It's the equivalent of string.Concat(hello, " ", value, " ", value2, value, " ", ...);


      Man is a marvelous curiosity ... he thinks he is the Creator's pet ... he even believes the Creator loves him; has a passion for him; sits up nights to admire him; yes and watch over him and keep him out of trouble. He prays to him and thinks He listens. Isn't it a quaint idea. - Mark Twain

      A Offline
      A Offline
      Andy Brummer
      wrote on last edited by
      #37

      Only for small numbers of strings. If I remember correctly it is <= 3. Anyway, performance shouldn't be much of a concern with either method.


      This blanket smells like ham

      D 1 Reply Last reply
      0
      • D Dave Kreskowiak

        I don't buy it. I just don't see how any variant of

        Dim sqlUpdate As String = "UPDATE ls_orderitems SET OrderItemRetailPrice = '" & _
        Trim(PartRetailPrice) & "', OrderItemSalePrice = '" & Trim(PartSalePrice) & _
        "' WHERE OrderItemPartNum = '" & Trim(PartNum) & "', OrderItemSource = '" & _
        Trim(PartSource) & "', OrderType = 'Ron Ayers MotorSports'"

        can possibly be considered "easier to debug".

        A guide to posting questions on CodeProject[^]
        Dave Kreskowiak Microsoft MVP Visual Developer - Visual Basic
             2006, 2007

        J Offline
        J Offline
        jschell
        wrote on last edited by
        #38

        Dave Kreskowiak wrote:

        I don't buy it. I just don't see how any variant of Dim sqlUpdate ...

        I don't see how any variant of that is not subject to sql injection attacks. Consequently it isn't clear to me that that particular example proves anything.

        D 1 Reply Last reply
        0
        • D Dave Kreskowiak

          I don't buy it. I just don't see how any variant of

          Dim sqlUpdate As String = "UPDATE ls_orderitems SET OrderItemRetailPrice = '" & _
          Trim(PartRetailPrice) & "', OrderItemSalePrice = '" & Trim(PartSalePrice) & _
          "' WHERE OrderItemPartNum = '" & Trim(PartNum) & "', OrderItemSource = '" & _
          Trim(PartSource) & "', OrderType = 'Ron Ayers MotorSports'"

          can possibly be considered "easier to debug".

          A guide to posting questions on CodeProject[^]
          Dave Kreskowiak Microsoft MVP Visual Developer - Visual Basic
               2006, 2007

          A Offline
          A Offline
          Al Beback
          wrote on last edited by
          #39

          Dave Kreskowiak wrote:

          can possibly be considered "easier to debug".

          I never mentioned debugging. When you debug this, you step over that statement and look at the resulting string. It's the same when using Format.


          Man is a marvelous curiosity ... he thinks he is the Creator's pet ... he even believes the Creator loves him; has a passion for him; sits up nights to admire him; yes and watch over him and keep him out of trouble. He prays to him and thinks He listens. Isn't it a quaint idea. - Mark Twain

          D 1 Reply Last reply
          0
          • P PIEBALDconsult

            And don't forget ...value==null?"null":value.ToString()...

            A Offline
            A Offline
            Al Beback
            wrote on last edited by
            #40

            PIEBALDconsult wrote:

            And don't forget ...value==null?"null":value.ToString()...

            How do you handle that with format specifiers?


            Man is a marvelous curiosity ... he thinks he is the Creator's pet ... he even believes the Creator loves him; has a passion for him; sits up nights to admire him; yes and watch over him and keep him out of trouble. He prays to him and thinks He listens. Isn't it a quaint idea. - Mark Twain

            P 1 Reply Last reply
            0
            • A Al Beback

              Shog9 wrote:

              which of the above paragraphs do you prefer?

              1! :-D


              Man is a marvelous curiosity ... he thinks he is the Creator's pet ... he even believes the Creator loves him; has a passion for him; sits up nights to admire him; yes and watch over him and keep him out of trouble. He prays to him and thinks He listens. Isn't it a quaint idea. - Mark Twain

              S Offline
              S Offline
              Shog9 0
              wrote on last edited by
              #41

              Surprise surprise! ;P

              every night, i kneel at the foot of my bed and thank the Great Overseeing Politicians for protecting my freedoms by reducing their number, as if they were deer in a state park. -- Chris Losinger, Online Poker Players?

              1 Reply Last reply
              0
              • B Big Daddy Farang

                malharone wrote:

                Performance: string concat. is heavy, which does not happen in the string.format

                That's what I thought as well. Although the OP stated that the concat. approach was more efficient, but I'm not so sure I buy his reasoning for it. I think he's fishing for "5" votes. ;) BDF

                D Offline
                D Offline
                Daniel Grunwald
                wrote on last edited by
                #42

                string.Concat is the fastest way to concatenate strings. StringBuilder is not faster than string.Concat; only multiple Append calls to the same StringBuilder are more efficient than multiple calls to Concat for building a single string.

                B 1 Reply Last reply
                0
                • A Al Beback

                  Here's a simple code snippet (in C#):

                  string hello = "Hello";
                  string cp = "CP";
                  DateTime today = DateTime.Today;

                  // Desired result: "Hello CP! Today is Friday";

                  string option1 = string.Format("{0} {1}! Today is {3:dddd}", hello, cp, today);

                  string option2 = hello + " " + cp + "! Today is " + today.ToString("dddd");

                  Vote 1 if you prefer option1. Vote 5 if you prefer option2. I prefer option2 since it's 1. More readable 2. Less error-prone (note the subtle error in option1 which the compiler won't catch) 3. More efficient (no CPU cycles spent scanning the format string looking for matching curly braces). Cheers!


                  Man is a marvelous curiosity ... he thinks he is the Creator's pet ... he even believes the Creator loves him; has a passion for him; sits up nights to admire him; yes and watch over him and keep him out of trouble. He prays to him and thinks He listens. Isn't it a quaint idea. - Mark Twain

                  J Offline
                  J Offline
                  jschell
                  wrote on last edited by
                  #43

                  Al Beback wrote:

                  1. More readable

                  Entirely and completely subjective.

                  Al Beback wrote:

                  2. Less error-prone (note the subtle error in option1 which the compiler won't catch)

                  Perhaps. But you do have unit tests and system tests correct? If so then why are they not testing that code?

                  Al Beback wrote:

                  3. More efficient (no CPU cycles spent scanning the format string looking for matching curly braces).

                  If that is an actual performance bottleneck in your system then you have a very unusual system. Nothing in the above suggests an actual valid reason to choose either. As such it is a matter of personal choice. One real reason for choosing the Format version is because it support internationalization where the other does not. That of course is dependent on whether the application does have an international market and whether the multitude of other areas required for internationalization are actively being worked. And I can only note that actually moving this into a resource to support internationalization has many other possibilities for errors so one really better be testing everything.

                  1 Reply Last reply
                  0
                  • D Daniel Grunwald

                    string.Concat is the fastest way to concatenate strings. StringBuilder is not faster than string.Concat; only multiple Append calls to the same StringBuilder are more efficient than multiple calls to Concat for building a single string.

                    B Offline
                    B Offline
                    Big Daddy Farang
                    wrote on last edited by
                    #44

                    Thanks. That makes sense. Do you think it's even an issue in the very simple cases shown in the start of this thread? That's creating a string with a few concatenations versus String.Format. BDF

                    1 Reply Last reply
                    0
                    • A Al Beback

                      PIEBALDconsult wrote:

                      Well, if/when you use a Console.WriteLine(), would you use the format string and parameters?

                      No. I would still use concatenation for the same reasons (readability, stability, and efficiency).


                      Man is a marvelous curiosity ... he thinks he is the Creator's pet ... he even believes the Creator loves him; has a passion for him; sits up nights to admire him; yes and watch over him and keep him out of trouble. He prays to him and thinks He listens. Isn't it a quaint idea. - Mark Twain

                      P Offline
                      P Offline
                      PIEBALDconsult
                      wrote on last edited by
                      #45

                      Well consistency is good too.

                      1 Reply Last reply
                      0
                      • A Andy Brummer

                        Only for small numbers of strings. If I remember correctly it is <= 3. Anyway, performance shouldn't be much of a concern with either method.


                        This blanket smells like ham

                        D Offline
                        D Offline
                        Daniel Grunwald
                        wrote on last edited by
                        #46

                        It's <= 4. For more strings, it's still a single call to Concat(string[]), which means a temporary string array is created. This is still better than creating a temporary StringBuilder object, which creates multiple String objects when it needs to make the string larger. I only use StringBuilder when it is not possible to use a single call to string.Concat - e.g. in a loop like this: StringBuilder b = new StringBuilder(); foreach (SomeClass c in list) { b.Append(c.Text); b.Append(','); } return b.ToString(); The algorithm is O(n), with multiple string.Concat calls it would be O(n^2). Somehow the advice that StringBuilder should be used in those cases became the urban legend "StringBuilder is always faster in a loop". The advice only applies if the loop is appending to a single string; in cases where one would need multiple StringBuilder objects (or where one would re-use a StringBuilder object after calling ToString() on it), string.Concat is faster: string[] ConcatPairs(string[] a, string[] b) { string[] c = new string[a.Length]; for (int i = 0; i < a.Length; i++) { c[i] = a[i] + b[i]; } return c; } And String.Format is a real performance killer: not only is it required to parse the format string, it also puts all arguments in a temporary object[] array (value types are boxed if required), tries to cast all arguments to IFormattable, then calls ToString() on them (a virtual method call, or interface method call if the object implements IFormattable). And in the end it uses StringBuilder for the concatenation (since string.Format contains a loop appending to the same string), which even alone is slower than a single string.Concat call.

                        A 1 Reply Last reply
                        0
                        • A Al Beback

                          Here's a simple code snippet (in C#):

                          string hello = "Hello";
                          string cp = "CP";
                          DateTime today = DateTime.Today;

                          // Desired result: "Hello CP! Today is Friday";

                          string option1 = string.Format("{0} {1}! Today is {3:dddd}", hello, cp, today);

                          string option2 = hello + " " + cp + "! Today is " + today.ToString("dddd");

                          Vote 1 if you prefer option1. Vote 5 if you prefer option2. I prefer option2 since it's 1. More readable 2. Less error-prone (note the subtle error in option1 which the compiler won't catch) 3. More efficient (no CPU cycles spent scanning the format string looking for matching curly braces). Cheers!


                          Man is a marvelous curiosity ... he thinks he is the Creator's pet ... he even believes the Creator loves him; has a passion for him; sits up nights to admire him; yes and watch over him and keep him out of trouble. He prays to him and thinks He listens. Isn't it a quaint idea. - Mark Twain

                          C Offline
                          C Offline
                          Chris Maunder
                          wrote on last edited by
                          #47

                          No Option #3: Use a StringBuilder?

                          cheers, Chris Maunder

                          CodeProject.com : C++ MVP

                          A 1 Reply Last reply
                          0
                          • C Chris Maunder

                            No Option #3: Use a StringBuilder?

                            cheers, Chris Maunder

                            CodeProject.com : C++ MVP

                            A Offline
                            A Offline
                            Al Beback
                            wrote on last edited by
                            #48

                            Chris Maunder wrote:

                            No Option #3: Use a StringBuilder?

                            No. StringBuilder is suitable for appending to an existing string. In my example I append a bunch of strings to create a new one.


                            Man is a marvelous curiosity ... he thinks he is the Creator's pet ... he even believes the Creator loves him; has a passion for him; sits up nights to admire him; yes and watch over him and keep him out of trouble. He prays to him and thinks He listens. Isn't it a quaint idea. - Mark Twain

                            1 Reply Last reply
                            0
                            • A Al Beback

                              PIEBALDconsult wrote:

                              And don't forget ...value==null?"null":value.ToString()...

                              How do you handle that with format specifiers?


                              Man is a marvelous curiosity ... he thinks he is the Creator's pet ... he even believes the Creator loves him; has a passion for him; sits up nights to admire him; yes and watch over him and keep him out of trouble. He prays to him and thinks He listens. Isn't it a quaint idea. - Mark Twain

                              P Offline
                              P Offline
                              PIEBALDconsult
                              wrote on last edited by
                              #49

                              It's not so much the format string. But in Option2 it makes determining the result even harder and it needs to be enclosed in parentheses or it'll eat the rest of the line. (Won't it? The + having precedence over the ?: )

                              1 Reply Last reply
                              0
                              • J jschell

                                Dave Kreskowiak wrote:

                                I don't buy it. I just don't see how any variant of Dim sqlUpdate ...

                                I don't see how any variant of that is not subject to sql injection attacks. Consequently it isn't clear to me that that particular example proves anything.

                                D Offline
                                D Offline
                                Dave Kreskowiak
                                wrote on last edited by
                                #50

                                You're missing the point. Forget that it's SQL. Imagine writing that for output to a line printer.

                                A guide to posting questions on CodeProject[^]
                                Dave Kreskowiak Microsoft MVP Visual Developer - Visual Basic
                                     2006, 2007

                                1 Reply Last reply
                                0
                                • P PIEBALDconsult

                                  Oh, well for that you need parameters anyway.

                                  D Offline
                                  D Offline
                                  Dave Kreskowiak
                                  wrote on last edited by
                                  #51

                                  Forget that it's SQL. Imagine writing that for output to line printer.

                                  A guide to posting questions on CodeProject[^]
                                  Dave Kreskowiak Microsoft MVP Visual Developer - Visual Basic
                                       2006, 2007

                                  P 1 Reply Last reply
                                  0
                                  • A Al Beback

                                    Dave Kreskowiak wrote:

                                    can possibly be considered "easier to debug".

                                    I never mentioned debugging. When you debug this, you step over that statement and look at the resulting string. It's the same when using Format.


                                    Man is a marvelous curiosity ... he thinks he is the Creator's pet ... he even believes the Creator loves him; has a passion for him; sits up nights to admire him; yes and watch over him and keep him out of trouble. He prays to him and thinks He listens. Isn't it a quaint idea. - Mark Twain

                                    D Offline
                                    D Offline
                                    Dave Kreskowiak
                                    wrote on last edited by
                                    #52

                                    Debugging takes many forms. You implied it when you said "less error-prone". Say the output on a report isn't correct. Go through that line and find the one or two spaces, or some other formatting or data accuracy issue, where the problem is occuring. Sorry, but I don't see how reading that line is easier than

                                    Dim sqlUpdate As String = String.Format("UPDATE {0} SET OrderItemRetailPrice = {1}, " & _
                                    "OrderItemSalePrice = {2} WHERE OrderItemPartNum = {3}, " & _
                                    "OrderItemSource = {4}, OrderType = {5}", _
                                    "ls_orderitems", PartRetailPrice, PartSalePrice, _
                                    PartNum, PartSource, "Ron Ayers MotorSports")

                                    A guide to posting questions on CodeProject[^]
                                    Dave Kreskowiak Microsoft MVP Visual Developer - Visual Basic
                                         2006, 2007

                                    1 Reply Last reply
                                    0
                                    • D Dave Kreskowiak

                                      Forget that it's SQL. Imagine writing that for output to line printer.

                                      A guide to posting questions on CodeProject[^]
                                      Dave Kreskowiak Microsoft MVP Visual Developer - Visual Basic
                                           2006, 2007

                                      P Offline
                                      P Offline
                                      PIEBALDconsult
                                      wrote on last edited by
                                      #53

                                      I'm in the Option1 camp.

                                      1 Reply Last reply
                                      0
                                      • D Daniel Grunwald

                                        It's <= 4. For more strings, it's still a single call to Concat(string[]), which means a temporary string array is created. This is still better than creating a temporary StringBuilder object, which creates multiple String objects when it needs to make the string larger. I only use StringBuilder when it is not possible to use a single call to string.Concat - e.g. in a loop like this: StringBuilder b = new StringBuilder(); foreach (SomeClass c in list) { b.Append(c.Text); b.Append(','); } return b.ToString(); The algorithm is O(n), with multiple string.Concat calls it would be O(n^2). Somehow the advice that StringBuilder should be used in those cases became the urban legend "StringBuilder is always faster in a loop". The advice only applies if the loop is appending to a single string; in cases where one would need multiple StringBuilder objects (or where one would re-use a StringBuilder object after calling ToString() on it), string.Concat is faster: string[] ConcatPairs(string[] a, string[] b) { string[] c = new string[a.Length]; for (int i = 0; i < a.Length; i++) { c[i] = a[i] + b[i]; } return c; } And String.Format is a real performance killer: not only is it required to parse the format string, it also puts all arguments in a temporary object[] array (value types are boxed if required), tries to cast all arguments to IFormattable, then calls ToString() on them (a virtual method call, or interface method call if the object implements IFormattable). And in the end it uses StringBuilder for the concatenation (since string.Format contains a loop appending to the same string), which even alone is slower than a single string.Concat call.

                                        A Offline
                                        A Offline
                                        Andy Brummer
                                        wrote on last edited by
                                        #54

                                        Good to know, the last info I saw on it was in the 1.0 days, when concat was only used for short strings of +'s after that it handled it as coded. It's good to hear that C# is getting smarter.

                                        Daniel Grunwald wrote:

                                        And String.Format is a real performance killer

                                        I've still never seen that in a real world application even ASP.NET pages handling hundreds of requests per second.


                                        This blanket smells like ham

                                        D 1 Reply Last reply
                                        0
                                        • A Al Beback

                                          Here's a simple code snippet (in C#):

                                          string hello = "Hello";
                                          string cp = "CP";
                                          DateTime today = DateTime.Today;

                                          // Desired result: "Hello CP! Today is Friday";

                                          string option1 = string.Format("{0} {1}! Today is {3:dddd}", hello, cp, today);

                                          string option2 = hello + " " + cp + "! Today is " + today.ToString("dddd");

                                          Vote 1 if you prefer option1. Vote 5 if you prefer option2. I prefer option2 since it's 1. More readable 2. Less error-prone (note the subtle error in option1 which the compiler won't catch) 3. More efficient (no CPU cycles spent scanning the format string looking for matching curly braces). Cheers!


                                          Man is a marvelous curiosity ... he thinks he is the Creator's pet ... he even believes the Creator loves him; has a passion for him; sits up nights to admire him; yes and watch over him and keep him out of trouble. He prays to him and thinks He listens. Isn't it a quaint idea. - Mark Twain

                                          V Offline
                                          V Offline
                                          Vasudevan Deepak Kumar
                                          wrote on last edited by
                                          #55

                                          Glaring misconception or a deliberate misguiding in the forum. String concatenations are always heavy. Always use either string.Format or StringBuilder. The compiler and runtime would love you for the kindness and friendliness.

                                          Vasudevan Deepak Kumar Personal Homepage Tech Gossips

                                          D A 2 Replies Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups