February 16, 2011

Measuring memory cunsumption

When using any object oriented programming language you sooner or later start using your own objects. But when creating your own class - more complex class that uses a lot of other objects, it may be a good idea to know how much memory your object cunsumes - You may want to maintain thousands of your objects in some collection for some time and it costs some memory..

A good way to get to know how much memory your object eats is using GetTotalMemory() method in System.GC.

long memoryStart = System.GC.GetTotalMemory(true);

// Generate some of your objects
ICollection<myobject> myObjects = List<myobject>();
for (int i = 0; i < 10000; i++)
  myObjects.Add(new MyObject);

long memoryEnd = System.GC.GetTotalMemory(true);

MessageBox.Show((memoryEnd - memoryStart).ToString());

That gives you how much memory consume 10 000 objects of your class. Divide it by 10 000 and it's the memory consumption of one object.


  1. Thanks for the tip. Good method to check your memory consumption!

  2. Very interesting, will bear that in mind IF i can remember it.