Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Size of object in memory [duplicate]

Tags:

c#

.net

Possible Duplicate:
How to get object size in memory?

Is it possible to know, obviously at runtime, the memory taken by an object? How? Specifically I'd like to know the amount of RAM occupied.

like image 488
pistacchio Avatar asked Dec 05 '22 18:12

pistacchio


2 Answers

For value types use sizeof(object value)

For unmanaged objects 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 way to get the size of RAM they use for 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 a profiler would be the best.

like image 115
papaiatis Avatar answered Dec 10 '22 10:12

papaiatis


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

like image 23
Beatles1692 Avatar answered Dec 10 '22 11:12

Beatles1692