I understand the difference between String
and StringBuilder
(StringBuilder
being mutable) but is there a large performance difference between the two?
The program I’m working on has a lot of case driven string appends (500+). Is using StringBuilder
a better choice?
Consider 'The Sad Tragedy of Micro-Optimization Theater'.
My approach has always been to use StringBuilder when concatenating 4 or more strings OR When I don't know how may concatenations are to take place.
Good performance related article on it here
I believe StringBuilder is faster if you have more than 4 strings you need to append together. Plus it can do some cool things like AppendLine.
StringBuilder
is significantly more efficient but you will not see that performance unless you are doing a large amount of string modification.Below is a quick chunk of code to give an example of the performance. As you can see you really only start to see a major performance increase when you get into large iterations.
As you can see the 200,000 iterations took 22 seconds while the 1 million iterations using the
StringBuilder
was almost instant.Result of the above code:
To clarify what Gillian said about 4 string, if you have something like this:
then it would be faster using strings and the plus operator. This is because (like Java, as Eric points out), it internally uses StringBuilder automatically (Actually, it uses a primitive that StringBuilder also uses)
However, if what you are doing is closer to:
Then you need to explicitly use a StringBuilder. .Net doesn't automatically create a StringBuilder here, because it would be pointless. At the end of each line, "a" has to be an (immutable) string, so it would have to create and dispose a StringBuilder on each line. For speed, you'd need to use the same StringBuilder until you're done building:
StringBuilder is preferable IF you are doing multiple loops, or forks in your code pass... however, for PURE performance, if you can get away with a SINGLE string declaration, then that is much more performant.
For example:
is more performant than
In this case, StringBuild could be considered more maintainable, but is not more performant than the single string declaration.
9 times out of 10 though... use the string builder.
On a side note: string + var is also more performant that the string.Format approach (generally) that uses a StringBuilder internally (when in doubt... check reflector!)