Share via


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;
foo myFoo;

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 ...

Comments

  • Anonymous
    April 24, 2006
    I like this solution but it isn't very threadsafe...

    When another thread allocates (or worse causes the release of) memory your calculation might go wrong and give you the impression that the object has a negative size... (now that would be cool if it was true!)

    Read this to get more info: http://blogs.msdn.com/cbrumme/archive/2003/04/15/51326.aspx

    Cheers

    Erno