Determine Approximate Memory Used by an Object

Curious as to how much memory your object or list of objects is taking up?  Here’s a quick way to get an approximation:

 
long startMem = GC.GetTotalMemory(true);
 
SortedDictionary<string, MyClass> myDictionary = GenerateDictionary();
 
long endMem = GC.GetTotalMemory(true);
long byteSize = endMem - startMem;
long bytesPerItem = byteSize / myDictionary.Count;
 
Console.WriteLine("Starting memory: {0} bytes", startMem);
Console.WriteLine("Ending memory: {0} bytes", endMem);
Console.WriteLine("Approx dictionary size: {0} bytes", byteSize);
Console.WriteLine("Bytes per item: {0} bytes", bytesPerItem);

And off you go!

This entry was posted in C#. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *