We all know that concatenating strings can cause efficiency problems, especially in loops. I was taught to use StringBuilder
to prevent these problems.
So this:
str += someotherstring
Turns into this:
StringBuilder sb = new StringBuilder();
sb.AppendLine(someotherstring);
But it is my understanding that the CLR in the .NET framework 3.5 and later is smart enough to output the same IL for both approaches. So is there a reason I should be enforcing stringbuilder in my teams code reviews anymore?
Edit: I think Servy hit the nail on the head in the comments:
This is the case when concatenating a number of strings known at compile time. Because of that, when concatenating a number of strings known at compile time there is no need to use a SB. When concatenating a number of strings unknown at compile time, it cannot do that
This is because String is immutable - it cannot change its internal state. On the other hand StringBuilder is mutable. When you call append(..) it alters the internal char array, rather than creating a new string object.
StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.
Objects of String are immutable, and objects of StringBuffer and StringBuilder are mutable. StringBuffer and StringBuilder are similar, but StringBuilder is faster and preferred over StringBuffer for the single-threaded program. If thread safety is needed, then StringBuffer is used.
Although the score difference isn't much, we can notice that StringBuilder works faster. Fortunately, in simple cases, we don't need StringBuilder to put one String with another. Sometimes, static concatenation with + can actually replace StringBuilder.
No that is not always correct. I dont if you have check this How to improve string concatenation performance in Visual C#
However, the .NET Framework includes a StringBuilder class that is optimized for string concatenation. It provides the same benefits as using a character array in C/C++, as well as automatically growing the buffer size (if needed) and tracking the length for you. The sample application in this article demonstrates the use of the StringBuilder class and compares the performance to concatenation.
StringBuilder is preferable when you are doing multiple loops, or forks in your code pass.
Also check this
This block of code took 1484 milliseconds to run on my PC:
for (int i = 0; i <= 1000000; i++) { // Concat strings 3 times using StringBuilder StringBuilder s = new StringBuilder(); s.Append(i.ToString()); s.Append(i.ToString()); s.Append(i.ToString()); }
And this one, using traditional concatenation, took slightly less time (1344 milliseconds):
for (int i = 0; i <= 1000000; i++) { // Concat strings 3 times using traditional concatenation string s = i.ToString(); s = s + i.ToString(); s = s + i.ToString(); }
The above data suggests that StringBuilder only starts to work faster once the number of concatenations exceed 3.
There is great link in comments posted by Tim which says about the
So, when should you use StringBuilder, and when should you use the string concatenation operators?
- Definitely use StringBuilder when you're concatenating in a non-trivial loop - especially if you don't know for sure (at compile time) how many iterations you'll make through the loop. For example, reading a file a character at a time, building up a string as you go using the += operator is potentially performance suicide.
- Definitely use the concatenation operator when you can (readably) specify everything which needs to be concatenated in one statement. (If you have an array of things to concatenate, consider calling String.Concat explicitly - or String.Join if you need a delimiter.)
- Don't be afraid to break literals up into several concatenated bits - the result will be the same. You can aid readability by breaking a long literal into several lines, for instance, with no harm to performance.
- If you need the intermediate results of the concatenation for something other than feeding the next iteration of concatenation, StringBuilder isn't going to help you. For instance, if you build up a full name from a first name and a last name, and then add a third piece of information (the nickname, maybe) to the end, you'll only benefit from using StringBuilder if you don't need the (first name + last name) string for other purpose (as we do in the example which creates a Person object).
- If you just have a few concatenations to do, and you really want to do them in separate statements, it doesn't really matter which way you go. Which way is more efficient will depend on the number of concatenations the sizes of string involved, and what order they're concatenated in. If you really believe that piece of code to be a performance bottleneck, profile or benchmark it both ways.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With