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?
Source: MSDN
StringBuilder
is better for building up a string from many non-constant values.If you're building up a string from a lot of constant values, such as multiple lines of values in an HTML or XML document or other chunks of text, you can get away with just appending to the same string, because almost all compilers do "constant folding", a process of reducing the parse tree when you have a bunch of constant manipulation (it's also used when you write something like
int minutesPerYear = 24 * 365 * 60
). And for simple cases with non-constant values appended to each other, the .NET compiler will reduce your code to something similar to whatStringBuilder
does.But when your append can't be reduced to something simpler by the compiler, you'll want a
StringBuilder
. As fizch points out, that's more likely to happen inside of a loop.Yes, the performance difference is significant. See the KB article "How to improve string concatenation performance in Visual C#".
I have always tried to code for clarity first, and then optimize for performance later. That's much easier than doing it the other way around! However, having seen the enormous performance difference in my applications between the two, I now think about it a little more carefully.
Luckily, it's relatively straightforward to run performance analysis on your code to see where you're spending the time, and then to modify it to use
StringBuilder
where needed.In .NET, StringBuilder is still faster than appending strings. I'm pretty sure that in Java, they just create a StringBuffer under the hood when you append strings, so there's isn't really a difference. I'm not sure why they haven't done this in .NET yet.
String and StringBuilder are actually both immutable, the StringBuilder has built in buffers which allow its size to be managed more efficiently. When the StringBuilder needs to resize is when it is re-allocated on the heap. By default it is sized to 16 characters, you can set this in the constructor.
eg.
StringBuilder sb = new StringBuilder(50);
If you're doing a lot of string concatenation, use a StringBuilder. When you concatenate with a String, you create a new String each time, using up more memory.
Alex