Search code examples
c#.netstringperformancestring-interning

String interning in .NET Framework - What are the benefits and when to use interning


I want to know the process and internals of string interning specific to .NET Framework. Would also like to know the benefits of using interning and the scenarios/situations where we should use string interning to improve the performance. Though I have studied interning from the Jeffery Richter's CLR book but I am still confused and would like to know it in more detail.

[Editing] to ask a specific question with a sample code as below:

private void MethodA()
{
    string s = "String"; // line 1 - interned literal as explained in the answer        

    //s.intern(); // line 2 - what would happen in line 3 if we uncomment this line, will it make any difference?
}

private bool MethodB(string compareThis)
{
    if (compareThis == "String") // line 3 - will this line use interning (with and without uncommenting line 2 above)?
    {
        return true;
    }
    return false;
}

Solution

  • Interning is an internal implementation detail. Unlike boxing, I do not think there is any benefit in knowing more than what you have read in Richter's book.

    Micro-optimisation benefits of interning strings manually are minimal hence is generally not recommended.

    This probably describes it:

    class Program
    {
        const string SomeString = "Some String"; // gets interned
    
        static void Main(string[] args)
        {
            var s1 = SomeString; // use interned string
            var s2 = SomeString; // use interned string
            var s = "String";
            var s3 = "Some " + s; // no interning 
    
            Console.WriteLine(s1 == s2); // uses interning comparison
            Console.WriteLine(s1 == s3); // do NOT use interning comparison
        }
    }