Search code examples
c#.netstring-interning

Intern string literals misunderstanding?


I dont understand :

MSDN says

http://msdn.microsoft.com/en-us/library/system.string.intern.aspx

Consequently, an instance of a literal string with a particular value only exists once in the system.

For example, if you assign the same literal string to several variables, the runtime retrieves the same reference to the literal string from the intern pool and assigns it to each variable.

Does this behavior is the Default (without intern ) ? or by using Intern method ?

  • If its default , so why will I want to use intern? (the instance will be once already...) ?

  • If its NOT default : if I write 1000 times this row :

    Console.WriteLine("lalala");

1 ) will I get 1000 occurrences of "lalala" in memory ? ( without using intern ...)

2) will "lalala" will eventually Gc'ed ?

3) Does "lalala" is already interned ? and if it does , why will i need to "get" it from the pool , and not just write "lalala" again ?

Im a bit confuse.


Solution

  • String literals get interned automatically (so, if your code contains "lalala" 1000 times, only one instance will exist).

    Such strings will not get GC'd and any time they are referenced the reference will be the interned one.


    string.Intern is there for strings that are not literals - say from user input or read from a file or database and that you know will be repeated very often and as such are worth interning for the lifetime of the process.