4

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.

Community
  • 1
  • 1
pistacchio
  • 56,889
  • 107
  • 278
  • 420
  • 1
    Use a [memory profiler](http://stackoverflow.com/search?q=%5Bc%23%5D+memory+profiler). – dtb Feb 17 '12 at 07:24
  • There are gazillions of dupes already. Please search before posting. [How to get object size in memory?](http://stackoverflow.com/questions/605621/how-to-get-object-size-in-memory). And also http://stackoverflow.com/questions/426396/how-much-memory-does-a-c-net-object-use. And also http://www.google.com/#hl=en&sclient=psy-ab&q=.net+size+of+object+in+memory&pbx=1&oq=.net+size+of+object+in+memory&aq=f&aqi=g1&aql=1&gs_sm=3&gs_upl=987l6327l0l6549l29l20l0l9l9l5l2247l4909l9.7.0.3.9-1l29l0&bav=on.2,or.r_gc.r_pw.r_qf.,cf.osb&fp=f0b85e3c6de8b9f9&biw=1440&bih=795 – Darin Dimitrov Feb 17 '12 at 07:31

2 Answers2

15

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.

papaiatis
  • 4,231
  • 4
  • 26
  • 38
  • it seems that result is always 0 when trying this code on List or arrays? – SHM Jan 25 '17 at 19:46
  • Note: This will give inaccurate results if `new foo()` allocates other stuff, which is sometimes the case. – James Ko Jan 29 '17 at 22:31
1

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.

Beatles1692
  • 5,214
  • 34
  • 65