I was going to post an answer on this other SO question but someone went ahead of me with the StringBuilder class, anyways, digressing...
I understand that strings in .NET are immutable, so creating a string and modifying it will actually create two different strings in memory, contrary to the StringBuilder Class
which maintains an internal buffer and creates a final string only on the ToString()
call. I also know that .NET interns each string, so only a copy will be created per string ever used in the application.
When you append a string to another one they are both being used in the application, so they both get interned (don't they?), the main reason for not to append strings with the concatenation operator is because you will end up with a whole bunch of strings in memory when done, each larger than the previous.
I understand that concatenating 01234
with 56789
will result in the following two strings in memory:
01234
0123456789
whilst using the StringBuilder
will only yield, due to interning:
01234
56789
obviously the second approach is better for performance but, how good is it actually? I mean, if you're creating a bigger string from a small list of values, why should I consider the StringBuilder
(that per se takes memory space)? Is it always good to use it? Or is there any good rule of thumbs as to when [not] to use it?