Glossary / String interning

String interning

String interning stores a canonical instance for equal string contents so repeated interned values can share one object. C# string literals are typically interned, and String.Intern/IsInterned expose the intern pool; interning can save duplicate storage in limited cases but has lifetime and memory-retention tradeoffs.

Equality and lifetime

String value equality compares character contents; reference identity is a separate concept. Interning makes equal interned strings refer to the same canonical object within the relevant runtime pool, but callers should compare strings by value unless identity is explicitly required. Dynamically interning unbounded user input can retain strings for a long time and grow memory use; pool implementation/lifetime behavior is runtime-specific.

The compiler/runtime may intern literals, but do not assume arbitrary runtime-created strings are interned. String.Intern can canonicalize a string; String.IsInterned checks for an existing interned instance. Modern .NET has nuanced pool lifetime behavior, so avoid relying on undocumented memory reclamation details.

Engineering guidance

Use interning only after profiling demonstrates a real memory benefit for a bounded vocabulary. Prefer dictionaries with appropriate comparers for canonical lookup. Never use reference equality as a substitute for value equality in general string logic. Avoid interning attacker-controlled or unbounded values.

Interview questions

  1. Are all strings interned? Literals generally are; arbitrary runtime strings are not necessarily.
  2. Should compare interned strings with ReferenceEquals? Usually no; use value equality for correct semantics.
  3. What is the risk of interning user input? Potential unbounded retention and memory growth.
  4. What does IsInterned return? Existing canonical string if present; otherwise null.
  5. When use it? Rarely, for a profiled, bounded set of repeated strings.

References