Geeks With Blogs
Rohit Gupta Engaging talk on Microsoft Technologies ....My Resume
  • Always try to use string.Compare() method for testing string equality and inequality
  • use string.CompareOrdinal() method for case sensitive string comparisons
  • when returning string from a method call insure that you never return “null” return string.Empty instead
  • Always initialize strings to string.Empty
  • when instantiating StringBuilder use the overloaded constructor to specify the initial capacity
  • Prefer string.format when concatenating value types into strings
   1: int number = 4545;
   2: string x = string.Format("{0} is a even number", number);
   3: //above is better than using
   4: string y = number.ToString() + " is a even number";

  • Use BitArray instead of using Array of booleans
  • use for loop for iterating over arrays, use foreach for iterating over collections
  • Set initial capacity for StringBuilder, SortedList, HashTable, ArrayList, Queue, Stack etc
  • First add all elements to HashTable and then create Sortedlist from this HashTable, since adding to SortedList directly is very expensive
  • Use DictionaryEntry to iterate over Hastable entries
  • Garbage Collector settings: In .Net there are 2 versions of the garbage collector, Workstation Garbage collector (used on single processor systems) and Server garbage collector (used on multi processor systems. Server garbage collector pauses app during GC and uses 1 thread and 1 managed heap for each CPU. The workstation garbage collector minimizes the pauses since it runs the GC concurrently with the app’s worker threads.
  • On single CPU machine, Workstation GC and Server GC behave the same way, but you can prevent the GC from running concurrently with the App threads by using this config in app.config or machine.config:
   1: <configuration>
   2:     <runtime>
   3:         <gcConcurrent enabled="false"/>
   4:     </runtime>
   5: </configuration>

  • By default, non-interactive apps like Windows Services, .NET Remoting apps use Workstation GC. Force such apps (running on multi core CPU machines) to use the server GC by adding the following to app.config:
   1: <configuration>
   2:     <runtime>
   3:         <gcServer enabled="true"/>
   4:     </runtime>
   5: </configuration>

  • WekReference: Use WeaKReference to create cache versions of your objects. weak references are references to objects that last until the point that GC does not collect them, once GC runs, then these objects need to be repopulated from original source. Here is an example of cached File:
   1: public class CachedTextFile
   2: {
   3:     public readonly string FileName;
   4:     WeakReference wrText;
   5:     public CachedTextFile(string filename)
   6:     {
   7:         this.FileName = filename;
   8:     }
  10:     private string ReadFile()
  11:     {
  12:         string text = string.Empty;
  13:         using (StreamReader sr = new StreamReader(FileName))
  14:         {
  15:             text = sr.ReadToEnd();
  16:         }
  17:         wrText = new WeakReference(text);
  18:         return text;
  19:     }
  21:     public string GetText()
  22:     {
  23:         object text = null;
  24:         //check weak reference
  25:         if (wrText != null)
  26:             text = wrText.Target;
  27:         if (text != null)
  28:         {
  29:             //string still in cache
  30:             return text.ToString();
  31:         }
  32:         else
  33:         {
  34:             //read from disk
  35:             return ReadFile();
  36:         }
  37:     }
  38: }
  41:         CachedTextFile cacheFile = new CachedTextFile(@"C:\temp\test.txt");
  42:        // this is the first call hence gets the text from disk, instead of memory/cache
  43:         Console.WriteLine(cacheFile.GetText());
  44:         //force garbage collection manually
  45:         GC.Collect();
  46:         GC.WaitForPendingFinalizers();
  47:         //following causes the app to read the file again
  48:         Console.WriteLine(cacheFile.GetText());
  • Dont create/destroy large objects (objects with size greater than 85000bytes) frequently, since such objects get allocated on the Large Object Heap which isn’t freed by the GC. Consider splitting large objects into 2 or more smaller objects like Partitioned Array’s.
Posted on Friday, March 6, 2009 2:30 PM | Back to top

Comments on this post: Some tips on .NET Memory usage

# re: Some tips on .NET Memory usage
Requesting Gravatar...
Very interesting article.. Sure I can use some hints that am aware of now!
Left by Shaurya Anand on Mar 07, 2009 4:11 AM

# re: Some tips on .NET Memory usage
Requesting Gravatar...
Hi. An interesting blog post but there's a point that I don't understand :

"Prefer string.format when concatenating value types into strings"

In your code (line4) .ToString() is redundant.
string y = number + " is a even number"; is just fine.
string.Format is slower in this case and to be honest I don't like it.
I would recommend to use it only when you have formatting(numbers, dates) but in this case we have simple concatenation of two strings. I think the plus or the StringBuilder(depending on the numbers of '+') is far better in this simple scenario.
Left by Petar Petrov on Mar 09, 2009 4:30 AM

Your comment:
 (will show your gravatar)

Copyright © Rohit Gupta | Powered by: