Tuesday, 2 February 2016

ASP.NET Tips #77 - Avoid duplicate string reference issues

String referencing duplication is one of the major memory hogging performance issues. String interning is a useful solution if you're generating a lot of strings at runtime that are likely to be the same. It calls IsInterned to see if an interned string exists as follows:

class Program
{
   static void Main()
   {
      // A.
      // String generated at runtime.
      // Is not unique in string pool
      string s1 = new StringBuilder().Append("cat").Append(" and dog").ToString();
      // B.
      // Interned string added at runtime.
      // Is unique in string pool.
      string s2 = string.Intern(s1);
   }
}

My own benchmarking showed that string interning can improve performance by more than four times when the string comparison is always true.

No comments :

Post a comment