how C#: Strings with same contents
I have heard and read that a string can not be changed (immutable?). That should be correct I guess. But I have also heard that two strings with the same contents share the same memory-space (or what you call it). Is this correct?
And if so, does that mean that if I create a List with thousands of strings, it wouldn’t really take up much space at all if most of those strings were equal to each other?
EDIT: In the answer below I’ve referred to the intern pool as being AppDomain-specific; I’m pretty sure that’s what I’ve observed before, but the MSDN docs for String.Intern suggest that there’s a single intern pool for the whole process, making this even more important.
(I was going to add this as a comment, but I think it’s an important enough point to need an extra answer…)
As others have explained, string interning occurs for all string literals, but not on “dynamically created” strings (e.g. those read from a database or file, or built using
However, I wouldn’t suggest calling
You’d then just use something like:
(Note that the pool isn’t thread-safe; normal usage wouldn’t need it to be.)
This way you can throw away your pool as soon as you no longer need it, rather than having a potentially large number of strings in memory forever. You could also make it smarter, implementing an LRU cache or something if you really wanted to.
EDIT: Just to clarify why this is better than using
Here you get the benefit of multiple strings in the same file only existing once in memory (or at least, only getting past gen0 once) but you don’t pollute a “global” resource (the intern pool).