When to use StringBuilder?

I understand the benefits of StringBuilder.

But if I want to concatenate 2 strings, then I assume it is better (faster) to do this without StringBuilder. Is it correct?

At what point (number of lines) is it better to use StringBuilder?

+68
stringbuilder c #
Dec 01 '09 at 12:08
source share
11 answers

I warmly invite you to read The Sad Tragedy of the Micro-Optimization Theater by Jeff Atwood.

It handles Simple Concatenation vs. StringBuilder and other methods.

Now, if you want to see some numbers and graphs, follow the link;)

+71
Dec 01 '09 at 12:12
source share
β€” -

But if I want to concatenate 2 strings, then I assume that it is better (faster) to do this without StringBuilder. Is it correct?

This is really correct, you can find out why this is explained very well:

http://www.yoda.arachsys.com/csharp/stringbuilder.html

Calculated: if you can concatenate rows at a time, for example

var result = a + " " + b + " " + c + .. 

you are better off without stringbuilder just for copying (the length of the resulting string is calculated in advance);

For structures like

 var result = a; result += " "; result += b; result += " "; result += c; .. 

new objects are created every time, so you should consider StringBuilder.

At the end of the article, these rules of thumb are summarized:

Thumb rules

So, when should you use StringBuilder, and when should you use string of concatenation operators?

  • You should definitely use StringBuilder when you join in a non-trivial loop - especially if you don't know for sure (at compile time) how many iterations you will perform through the loop. For example, reading file a at a time, creating a line when you use the + = operator is potentially suicidal.

  • Definitely use the concatenation operator when you can (read) specify everything that should be combined in a single statement. (If you have many things to come together, consider calling String.Concat explicitly - or String.Join if you need a separator.)

  • Do not be afraid to break literals into several concatenated bits - the result will be the same. You can help readability by breaking a long literal into multiple lines, for example, by using no harm to performance.

  • If you need intermediate results of concatenating something other than submitting the next iteration of concatenation, StringBuilder is not going to help you. For example, if you create a full name from the first name and surname, and then add the third part of the information (nickname, maybe) to the end, you only benefit from using StringBuilder if you do not need (name + surname) string for other purposes (as we we do this in the example that creates the Person object).

  • If you just have a few concatenations to do, and you really want to do them in separate statements, it’s not really what direction you are going. Which path is more efficient will depend on the number of concatenations of the sizes of the string involved, and what order they are combined. If you really believe that part of the code should be a bottleneck, profile or compare it in both directions.

+40
Dec 01 '09 at 12:12
source share

System.String is an immutable object - this means that whenever you change its contents, it allocates a new line, and this takes time (and memory?). Using StringBuilder, you modify the actual contents of an object without highlighting a new one.

So use StringBuilder when you need to make many changes to a string.

+11
Dec 01 '09 at 12:12
source share

Not really ... you should use StringBuilder if you concatenate large strings or you have a lot of concatenations, for example in a loop.

+8
Dec 01 '09 at 12:11
source share
  • If you concatenate strings in a loop, you should use StringBuilder instead of a regular string
  • In the case of a single concatenation, you may not see the difference in execution time at all

Here is a simple test application to prove the point:

 class Program { static void Main(string[] args) { const int testLength = 30000; var StartTime = DateTime.Now; //TEST 1 - String StartTime = DateTime.Now; String tString = "test string"; for (int i = 0; i < testLength; i++) { tString += i.ToString(); } Console.WriteLine((DateTime.Now - StartTime).TotalMilliseconds.ToString()); //result: 2000 ms //TEST 2 - StringBuilder StartTime = DateTime.Now; StringBuilder tSB = new StringBuilder("test string"); for (int i = 0; i < testLength; i++) { tSB.Append(i.ToString()); } Console.WriteLine((DateTime.Now - StartTime).TotalMilliseconds.ToString()); //result: 4 ms Console.ReadLine(); } } 

Results:

  • 30'000 iterations

    • String - 2000 ms
    • StringBuilder - 4 ms
  • 1000 iterations

    • String - 2 ms
    • StringBuilder - 1 ms
  • 500 iterations

    • String - 0 ms
    • StringBuilder - 0 ms
+5
Sep 19 '16 at 16:19
source share

But if I want to concatenate 2 strings, then I assume that it is better (faster) to do this without StringBuilder. Is it correct?

Yes. But more importantly, it’s much more convenient to use vanilla strings in such situations. On the other hand, using this in a loop makes sense and can also be as readable as concatenation.

The identifier should be wary of rules of thumb indicating specific concatenation numbers as a threshold. Using it in loops (and only in loops) is probably just as useful, easier to remember and make more sense.

+4
Dec 01 '09 at 12:11
source share

There is no final answer, just thumb rules. My personal rules go something like this:

  • If concatenating in a loop, always use StringBuilder .
  • If strings are large, always use StringBuilder .
  • If the concatenation code is neat and readable on the screen, then this is probably normal.
    If this is not the case, use StringBuilder .
+4
Dec 01 '09 at 12:16
source share

Rephrase

Then you will count to three, no more, no less. Three is the number you need to count, and the number of counts should be three. Four do not count, and do not count two, except that you go to three. Once the number three, being the third number, is reached, then swallow your Holy Hand grenade of Antioch

I usually use a string builder for any block of code that will result in the concatenation of three or more lines.

+4
Dec 01 '09 at 12:22
source share

As long as you can physically enter the number of concatenations (a + b + c ...), this should not matter much. Squared N (at N = 10) is a 100-fold slowdown that should not be too bad.

The big problem is that you concatenate hundreds of lines. With N = 100, you get a slowdown of 10,000 times. This is pretty bad.

+3
Dec 01 '09 at 12:21
source share

I do not think that there is a fine line between when to use or when not to do it. Unless, of course, someone did not complete some extensive tests to come out with golden conditions.

For me, I will not use StringBuilder if I simply concatenate 2 huge strings. If the cycle is with an uncertain count, I will most likely even if the cycle may be small.

+2
Dec 01 '09 at 12:17
source share

The only concatenation is not to use stringbuilder. Usually I used 5 concatenations as a rule.

+1
Dec 01 '09 at 12:10
source share



All Articles