Thursday 4 February 2016

ASP.NET Tips #78 - Dispose of unmanaged resources

File I/O, network resources, database connections, etc, should be disposed of once their usage is complete, rather than waiting for the Garbage Collector to handle them. This can take anything from milliseconds to minutes, depending on the rate you consume memory in your code. If you don't use a lot of, it will take a long time.

These types of resources typically implement the IDisposable interface so that unmanaged resources can be released once use of the object is complete.

Ideally, use a 'using' {...} block to automatically dispose the object once out of scope, or ensure you manually call Dispose().

For more information, see:

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.