What is string interning in .NET?
Quick Answer
Interning stores one shared instance of a string in an intern pool so identical string values reference the same object. String literals are interned automatically by the compiler; strings built at run time are not, unless you call string.Intern(). It saves memory when you have many duplicate strings but the pool lives for the process lifetime.
Interning means the runtime keeps a single copy of a given string value in a pool, so two variables with the same text can share the same object. String literals in your code are interned automatically at compile time — that's why ReferenceEquals on two "hi" literals is true. Strings you build at run time aren't, unless you call string.Intern. It can save memory when you have huge numbers of duplicate strings, like a tokeniser, but the pool never gets collected — it lives as long as the process — so interning lots of unique strings is effectively a memory leak.
string a = "hi"; string b = "hi"; ReferenceEquals(a, b)→true(both point at the interned literal).string c = new string("hi".ToCharArray()); ReferenceEquals(a, c)→false.string.Intern(c)returns the pooled reference;string.IsInterned(s)checks.- Trade-off: interned strings are never garbage collected — the pool is rooted for the app's life. Interning a flood of unique runtime strings is a leak.
- Legitimate use: a parser/tokeniser that produces the same few hundred identifiers millions of times. Otherwise leave it alone.