Reputation: 1710
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
Upvotes: 7
Views: 5942
Reputation: 172398
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.
Upvotes: 7
Reputation: 51355
Strings in .NET are immutable. Once constructed they cannot be modified later. If you want to modify a string you need to create a new one from the old one and throw away the old one.
A StringBuilder on the other hand can be thought of as a mutable string. Changing its contents after it is constructed is possible, and does not require allocating a whole new object.
The different performance characteristics usually do not surface when comparing the time taken to perform similar operations using a StringBuilder and string concatenation. The effect is more indirect: While string concatenation produces potentially lots of short-lived temporary objects, the StringBuilder doesn't. Consequently, using a StringBuilder can significantly reduce memory pressure on the managed heap, reducing the necessity for costly garbage collections.
It all depends on your application though and I will not try to give any generic advice. An application that performs a lot of string manipulations (like a web server) needs more attention than one that doesn't. If you understand how strings and a StringBuilder are different and the implications you should be in a good position to make judicious decisions. If in doubt: profile. But be sure to profile GC cycles as well.
Upvotes: 0
Reputation:
StringBuilder
will be used when you're concatenating an arbitrary amount of string values, for example. If this scenario sounds like your scenario then, yes, you should enforce the use of StringBuilder
.
Upvotes: 0
Reputation: 223217
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.
No. That is not necessary. You can't rely on compiler to optimize this in a loop. It is also better to use StringBuilder
since it will definitely be better in string concatenation and provides better readability.
Upvotes: 2