Course contentsShow
← C#
Lesson 1736 of 1,90816. Performance and DiagnosticsFree lesson

Mastering String Interning and Memory Reuse

Students will recognize when string pooling is beneficial and how to use it to reduce redundant memory usage.

In this lesson, you will learn how to drastically reduce memory overhead in high-throughput applications by reusing identical string instances through interning.

The Cost of String Redundancy

In .NET, strings are immutable and are stored on the managed heap. If your application frequently processes identical strings—such as unique keys, status codes, or repetitive configuration tokens—each individual instance consumes memory independently. If you have 10,000 instances of the string "Active", the runtime allocates memory for 10,000 separate objects, even though their contents are identical. This puts unnecessary pressure on the Garbage Collector (GC), particularly in the older generations.

Implementing String Interning

The string.Intern(string str) method allows you to force the runtime to point a string reference to a single, canonical instance stored in a private table called the intern pool. If an identical string already exists in the pool, the runtime returns that reference instead of allocating a new one.

string input1 = GetValueFromNetwork(); // e.g., "Status:Active"
string input2 = GetValueFromDatabase(); // e.g., "Status:Active"

// Without interning, these are two distinct objects in memory.
// By interning, we ensure both references point to the same memory address.
string pooled1 = string.Intern(input1);
string pooled2 = string.Intern(input2);

Console.WriteLine(ReferenceEquals(pooled1, pooled2)); // True

When to Use String Pooling

Interning isn't a silver bullet. Because the intern pool is managed by the Common Language Runtime (CLR) and is not easily cleared by the GC, interning arbitrary strings can actually lead to a memory leak where strings stay in memory for the life of the application.

You should utilize string interning only when:

  1. You have a high frequency of duplicate strings (e.g., thousands of objects sharing the same 50 possible category names).
  2. The set of unique strings is relatively small and stable.
  3. You are dealing with long-lived strings that would otherwise stay in memory anyway.

If your strings are transient or highly unique (like IDs or user input), avoid interning, as the overhead of managing the intern table will outweigh the memory savings.

Key Takeaway: Use string.Intern to collapse duplicate string objects into a single shared instance, but apply it cautiously only to high-frequency, static-like string values to prevent inflating the global intern pool.