[ACCEPTED]-Size of object in memory-.net

Accepted answer
Score: 15

For value types use sizeof(object value)

For unmanaged objects 4 use Marshal.SizeOf(object obj)

Unfortunately the two above will not get you the sizes of referenced objects.

For managed object: There is no direct 3 way to get the size of RAM they use for 2 managed objects, see: http://blogs.msdn.com/cbrumme/archive/2003/04/15/51326.aspx

Or alternatives:

System.GC.GetTotalMemory

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());

Source: http://blogs.msdn.com/b/mab/archive/2006/04/24/582666.aspx

Profiler

Using 1 a profiler would be the best.

Score: 1

You can use CLR Profiler to see the allocation size 5 for each type (not a specific object).There 4 are also some commercial products that can 3 help you monitor the usage of memory of 2 your program.JetBrains dotTrace and RedGate Ants are 1 some of them.

More Related questions