How does StringBuilder
work?
What does it do internally? Does it use unsafe code?
And why is it so fast (compared to the +
opera
StringBuilder
's implementation has changed between versions, I believe. Fundamentally though, it maintains a mutable structure of some form. I believe it used to use a string which was still being mutated (using internal methods) and would just make sure it would never be mutated after it was returned.
The reason StringBuilder
is faster than using string concatenation in a loop is precisely because of the mutability - it doesn't require a new string to be constructed after each mutation, which would mean copying all the data within the string etc.
For just a single concatenation, it's actually slightly more efficient to use +
than to use StringBuilder
. It's only when you're performing multiple operations and you don't really need the intermediate results that StringBuilder
shines.
See my article on StringBuilder for more information.