Question

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?

Was it helpful?

Solution

I also know that .NET interns each string

No, you got the wrong idea about interning. When you create a new string by, say, concatenating then the runtime does not go hunting through the table of interned strings to see if there might be a match. That would be grossly inefficient, too many cpu cycles for a very modest savings in GC heap space.

The only strings that are interned in a regular .NET app are the ones that started out as interned from the beginning. The ones that the compiler created from literals in your source code and added to the string table in the assembly metadata. You can explicitly intern a string with the String.Intern() method but that's a very rare thing to do.

You use StringBuilder to avoid generating too many temporary strings that have only a very short life span.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top