C# String Interning

String interning is a process where only one copy of each distinct string value is stored in memory. This can improve memory usage when there are many duplicate strings.

Key Topics

1. What is String Interning?

Interning allows strings with the same value to share the same memory reference.

2. Using String.Intern()

Example: Interning Strings

string str1 = "Hello";
string str2 = new string(new char[] { 'H', 'e', 'l', 'l', 'o' });
string internedStr2 = String.Intern(str2);
Console.WriteLine(object.ReferenceEquals(str1, str2));        // Outputs: False
Console.WriteLine(object.ReferenceEquals(str1, internedStr2)); // Outputs: True

3. Reference Equality

After interning, strings with the same content have the same reference.

Example: Reference Comparison

string a = "test";
string b = "test";
Console.WriteLine(object.ReferenceEquals(a, b)); // Outputs: True

Key Takeaways

  • String interning can save memory by storing only one instance of identical strings.
  • The CLR automatically interns string literals.
  • Use String.Intern() to intern dynamically created strings.
  • Be cautious when interning large numbers of unique strings, as it can increase memory usage.