How to determine size of .NET managed object in memory (like a sizeof for reference types)
An approximate way to determine the size of object usage in memory can be done by checking the total memory before and after the creation of the object. In the following example it is assumed you have a class named foo.
long StopBytes = 0;
long StartBytes = System.GC.GetTotalMemory(true);
myFoo = new foo();
StopBytes = System.GC.GetTotalMemory(true);
GC.KeepAlive(myFoo); // This ensure a reference to object keeps object in memory
MessageBox.Show("Size is " + ((long)(StopBytes - StartBytes)).ToString());
Anyone have better suggestions?
P.S. As one of the people that commentted, this is not thread-safe and should not be used in a production environment as how the CLR allocates memory can vary. Keep those comments coming ...