Size of object in memory

Possible duplicate:
How to get the size of an object in memory?

Is it possible, at runtime, to know the memory taken by an object? How? In particular, I would like to know the amount of RAM occupied.

+4
source share
2 answers

For value types, use sizeof(object value)

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

Unfortunately, the two above will not get the dimensions of the referenced objects.

For a managed entity: There is no direct way to get the size of RAM that they use for managed entities, 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 a profiler would be best.

+14
source

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

+1
source

Source: https://habr.com/ru/post/1396978/


All Articles