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. General Programming
  3. C#
  4. Which string is more preferred

Which string is more preferred

Scheduled Pinned Locked Moved C#
18 Posts 7 Posters 0 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.
  • H Offline
    H Offline
    humayunlalzad
    wrote on last edited by
    #1

    Hi All Is there any difference in the following three strings. Is any one of them more preferred over the other two.

    //concat string
    lblScore.Text = correctNums.ToString() + "/" + numberOfTurns.ToString();

    //Or
    //Format string
    lblScore.Text = String.Format("{0}/{1}", correctNums, numberOfTurns);

    //Or
    //Stringbuilder
    StringBuilder str = new StringBuilder();
    str.AppendFormat("{0}/{1}", correctNums, numberOfTurns);

    D G J P 4 Replies Last reply
    0
    • H humayunlalzad

      Hi All Is there any difference in the following three strings. Is any one of them more preferred over the other two.

      //concat string
      lblScore.Text = correctNums.ToString() + "/" + numberOfTurns.ToString();

      //Or
      //Format string
      lblScore.Text = String.Format("{0}/{1}", correctNums, numberOfTurns);

      //Or
      //Stringbuilder
      StringBuilder str = new StringBuilder();
      str.AppendFormat("{0}/{1}", correctNums, numberOfTurns);

      D Offline
      D Offline
      dan sh
      wrote on last edited by
      #2

      Read this[^] article. Might help you.

      The word "politics" describes the process so well: "Poli" in Latin meaning "many" and "tics" meaning "bloodsucking creatures."

      H 1 Reply Last reply
      0
      • H humayunlalzad

        Hi All Is there any difference in the following three strings. Is any one of them more preferred over the other two.

        //concat string
        lblScore.Text = correctNums.ToString() + "/" + numberOfTurns.ToString();

        //Or
        //Format string
        lblScore.Text = String.Format("{0}/{1}", correctNums, numberOfTurns);

        //Or
        //Stringbuilder
        StringBuilder str = new StringBuilder();
        str.AppendFormat("{0}/{1}", correctNums, numberOfTurns);

        G Offline
        G Offline
        Guffa
        wrote on last edited by
        #3

        The Concat method is slightly faster than the others. The Format method and your use of StringBuilder is virtually the same, as the Format method uses a StringBuilder and the AppendFormat method. When you send the values to the Format and AppendFormat methods, they will be boxed. That means that a new object is created on the heap and the integers are stored in this object. Using the Concat method avoids the boxing. If you want to use a StringBuilder, this is a better approach: lblScore.Text = new StringBuilder().Append(correctNums).Append('/').Append(numberOfTurns).ToString();

        Despite everything, the person most likely to be fooling you next is yourself.

        1 Reply Last reply
        0
        • H humayunlalzad

          Hi All Is there any difference in the following three strings. Is any one of them more preferred over the other two.

          //concat string
          lblScore.Text = correctNums.ToString() + "/" + numberOfTurns.ToString();

          //Or
          //Format string
          lblScore.Text = String.Format("{0}/{1}", correctNums, numberOfTurns);

          //Or
          //Stringbuilder
          StringBuilder str = new StringBuilder();
          str.AppendFormat("{0}/{1}", correctNums, numberOfTurns);

          J Offline
          J Offline
          J4amieC
          wrote on last edited by
          #4

          Number 2 is the right way, number 1 is the wrong way and number 3 does something entirely different to 1 & 2 (It does not assign a variable to lblScore). If it did assign str.ToString() to lblScore then it would be mostly the same as 2, but with the worthless overhead of creating a StringBuilder. If however you were appending a greater number of strings to the output then 3 would be the better way to approach the problem.

          N H G J 4 Replies Last reply
          0
          • J J4amieC

            Number 2 is the right way, number 1 is the wrong way and number 3 does something entirely different to 1 & 2 (It does not assign a variable to lblScore). If it did assign str.ToString() to lblScore then it would be mostly the same as 2, but with the worthless overhead of creating a StringBuilder. If however you were appending a greater number of strings to the output then 3 would be the better way to approach the problem.

            N Offline
            N Offline
            Not Active
            wrote on last edited by
            #5

            J4amieC wrote:

            Number 2 is the right way, number 1 is the wrong way

            I wouldn't say right or wrong, it's more of which is better for the given circumstance


            only two letters away from being an asset

            J 1 Reply Last reply
            0
            • N Not Active

              J4amieC wrote:

              Number 2 is the right way, number 1 is the wrong way

              I wouldn't say right or wrong, it's more of which is better for the given circumstance


              only two letters away from being an asset

              J Offline
              J Offline
              J4amieC
              wrote on last edited by
              #6

              Compiler changing concatenation with + to a stringbuilder asside, there is never a good reason to concatenate strings using +. Ever.

              N J 2 Replies Last reply
              0
              • D dan sh

                Read this[^] article. Might help you.

                The word "politics" describes the process so well: "Poli" in Latin meaning "many" and "tics" meaning "bloodsucking creatures."

                H Offline
                H Offline
                humayunlalzad
                wrote on last edited by
                #7

                Thanx D@nish that was a great article.

                1 Reply Last reply
                0
                • J J4amieC

                  Compiler changing concatenation with + to a stringbuilder asside, there is never a good reason to concatenate strings using +. Ever.

                  N Offline
                  N Offline
                  Not Active
                  wrote on last edited by
                  #8

                  I would disagree, its a matter of preference. I see nothing wrong with something like "Some string: " + x, depending on the circumstance it is being used in. As Guffa points out there may be some boxing that is occurring with StringBuilder and Format which could be avoided.


                  only two letters away from being an asset

                  J 1 Reply Last reply
                  0
                  • J J4amieC

                    Number 2 is the right way, number 1 is the wrong way and number 3 does something entirely different to 1 & 2 (It does not assign a variable to lblScore). If it did assign str.ToString() to lblScore then it would be mostly the same as 2, but with the worthless overhead of creating a StringBuilder. If however you were appending a greater number of strings to the output then 3 would be the better way to approach the problem.

                    H Offline
                    H Offline
                    humayunlalzad
                    wrote on last edited by
                    #9

                    j4amieC you are write I did not write the full code in the third case, but yes the StringBuilder does assign the text to the lblScore. Can you tell me why concatenating strings is not a good idea in this case. Does it leave string objects in memory? Or is there any other reason?

                    J 1 Reply Last reply
                    0
                    • H humayunlalzad

                      j4amieC you are write I did not write the full code in the third case, but yes the StringBuilder does assign the text to the lblScore. Can you tell me why concatenating strings is not a good idea in this case. Does it leave string objects in memory? Or is there any other reason?

                      J Offline
                      J Offline
                      J4amieC
                      wrote on last edited by
                      #10

                      humayunlalzad wrote:

                      Can you tell me why concatenating strings is not a good idea in this case.

                      Concatenate 10,000 strings using + and time it. Now concatenate the same 10,000 strings using a stringbuilder. Compare the times.

                      G 1 Reply Last reply
                      0
                      • N Not Active

                        I would disagree, its a matter of preference. I see nothing wrong with something like "Some string: " + x, depending on the circumstance it is being used in. As Guffa points out there may be some boxing that is occurring with StringBuilder and Format which could be avoided.


                        only two letters away from being an asset

                        J Offline
                        J Offline
                        J4amieC
                        wrote on last edited by
                        #11

                        Mark Nischalke wrote:

                        I see nothing wrong with something like "Some string: " + x

                        I see nothing right with it, and no reason to use it over either of: String.Format("Some string: {0}",x) or String.Concat("Some string: ",x)

                        G 1 Reply Last reply
                        0
                        • J J4amieC

                          Number 2 is the right way, number 1 is the wrong way and number 3 does something entirely different to 1 & 2 (It does not assign a variable to lblScore). If it did assign str.ToString() to lblScore then it would be mostly the same as 2, but with the worthless overhead of creating a StringBuilder. If however you were appending a greater number of strings to the output then 3 would be the better way to approach the problem.

                          G Offline
                          G Offline
                          Guffa
                          wrote on last edited by
                          #12

                          J4amieC wrote:

                          number 1 is the wrong way

                          Not at all. There is absolutely nothing wrong with using the Concat method to concatenate strings.

                          J4amieC wrote:

                          If it did assign str.ToString() to lblScore then it would be mostly the same as 2, but with the worthless overhead of creating a StringBuilder.

                          That is exactly how the String.Format method does it. The method that you say is the "right way" also has the worthless overhead of creating a StringBuilder, so you contradict yourself...

                          Despite everything, the person most likely to be fooling you next is yourself.

                          1 Reply Last reply
                          0
                          • J J4amieC

                            Number 2 is the right way, number 1 is the wrong way and number 3 does something entirely different to 1 & 2 (It does not assign a variable to lblScore). If it did assign str.ToString() to lblScore then it would be mostly the same as 2, but with the worthless overhead of creating a StringBuilder. If however you were appending a greater number of strings to the output then 3 would be the better way to approach the problem.

                            J Offline
                            J Offline
                            Jon Rista
                            wrote on last edited by
                            #13

                            Actually, #1 is the best way for his situation. A concatenation of up to 12 strings is much faster than either a StringBuilder or String.Format. StringBuilder incurrs overhead by keeping the strings on the heap until you call ToString(). String.Format has a variety of processing overhead that is not necessary in this case. When you know explicitly the number of string parts you need to join, and the order they will be joined in, a concat (up to 12 parts) will always be faster...significantly less overhead. Contrary to popular opinion, a single memory allocation and concat operation is involved in small concatenations. Only use an alternative method when the number of parts and/or their join order is unknown, or when you have more than 12 parts to join.

                            J 1 Reply Last reply
                            0
                            • J J4amieC

                              Compiler changing concatenation with + to a stringbuilder asside, there is never a good reason to concatenate strings using +. Ever.

                              J Offline
                              J Offline
                              Jon Rista
                              wrote on last edited by
                              #14

                              That is a COMPLETELY INVALID statement...I can't tell you how wrong that is. StringBuilder and String.Format are only useful and more performant in certain scenarios, not all. If you are joining thousands of string parts, StringBuilder will definitely be more efficient. If you are "formatting" a string, and you need localization support and the like, String.Format is your friend. However, for smaller concatenations where you know the number of parts involved, nothing beats the performance of a basic concat. Research it.

                              1 Reply Last reply
                              0
                              • J Jon Rista

                                Actually, #1 is the best way for his situation. A concatenation of up to 12 strings is much faster than either a StringBuilder or String.Format. StringBuilder incurrs overhead by keeping the strings on the heap until you call ToString(). String.Format has a variety of processing overhead that is not necessary in this case. When you know explicitly the number of string parts you need to join, and the order they will be joined in, a concat (up to 12 parts) will always be faster...significantly less overhead. Contrary to popular opinion, a single memory allocation and concat operation is involved in small concatenations. Only use an alternative method when the number of parts and/or their join order is unknown, or when you have more than 12 parts to join.

                                J Offline
                                J Offline
                                Jon Rista
                                wrote on last edited by
                                #15

                                My apologies...a string concat requires 2 allocations, not 1. For a comparison of concat vs. StringBuilder, take a look at this article: http://blogs.msdn.com/ricom/archive/2004/03/12/performance-quiz-1-of-a-series.aspx Concat: 4 calls, 2 allocations, 94 bytes StringBuilder: 30 calls, 5 allocations, 184 bytes

                                1 Reply Last reply
                                0
                                • J J4amieC

                                  humayunlalzad wrote:

                                  Can you tell me why concatenating strings is not a good idea in this case.

                                  Concatenate 10,000 strings using + and time it. Now concatenate the same 10,000 strings using a stringbuilder. Compare the times.

                                  G Offline
                                  G Offline
                                  Guffa
                                  wrote on last edited by
                                  #16

                                  J4amieC wrote:

                                  Concatenate 10,000 strings using + and time it. Now concatenate the same 10,000 strings using a stringbuilder. Compare the times.

                                  Here you go: Concatenating using + operator 10000 times: 3.50 ms. Concatenating using StringBuilder 10000 times: 5.03 ms. Concatenating using String.Format 10000 times: 5.97 ms.

                                  Despite everything, the person most likely to be fooling you next is yourself.

                                  1 Reply Last reply
                                  0
                                  • J J4amieC

                                    Mark Nischalke wrote:

                                    I see nothing wrong with something like "Some string: " + x

                                    I see nothing right with it, and no reason to use it over either of: String.Format("Some string: {0}",x) or String.Concat("Some string: ",x)

                                    G Offline
                                    G Offline
                                    Guffa
                                    wrote on last edited by
                                    #17

                                    You realise that using the + operator and using the String.Concat method produces identical code?

                                    Despite everything, the person most likely to be fooling you next is yourself.

                                    1 Reply Last reply
                                    0
                                    • H humayunlalzad

                                      Hi All Is there any difference in the following three strings. Is any one of them more preferred over the other two.

                                      //concat string
                                      lblScore.Text = correctNums.ToString() + "/" + numberOfTurns.ToString();

                                      //Or
                                      //Format string
                                      lblScore.Text = String.Format("{0}/{1}", correctNums, numberOfTurns);

                                      //Or
                                      //Stringbuilder
                                      StringBuilder str = new StringBuilder();
                                      str.AppendFormat("{0}/{1}", correctNums, numberOfTurns);

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

                                      If that's all I'm doing I use the second, but with more line breaks. I wouldn't be concerned about the relative efficiency of those particular statements; particularly when dealing with a GUI. But that's just me.

                                      1 Reply 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