views:

109

answers:

3

Hey all,

I'm wondering if there is a simple command or instruction in C#/.NET and/or Visual Studio that can tell me how much memory an individual object is taking up? I have a sneaking suspicion that the sizeof() operator is going to lie to me ... am I justified in this belief?

There is a somewhat related question here, but no definitive answer is given on how to measure an individual object

+2  A: 

There is no definitive way because it's not simple for just any type of object.

What if that object contains references to other objects? What if those other objects have other objects referencing them? Which object actually owns that memory space? Is it the one that created it or the last one to touch it? At any one point it could have different owners. Or do you just care about how much space the reference takes?

There is also a ton of questions that have asked this as well... a quick search turns up:

http://stackoverflow.com/questions/605621/how-to-get-object-size-in-memory

http://stackoverflow.com/questions/555929/c-memory-usage-of-an-object

http://stackoverflow.com/questions/324053/find-out-the-size-of-a-net-object

http://stackoverflow.com/questions/426396/how-much-memory-does-a-c-net-object-use

and the list goes on an on...

Kelsey
quite right, thanks for the pointers
Jeffrey Cameron
+2  A: 

There's no easy way and sizeof will only be good for value types. A typical object contains references to lists and other objects, so you would need to traverse all pointers in order to get the actual byte count, and add the pointer sizes as well.

You can check out the .Net Profiling API, or use a memory profiler like dotTrace. A memory profiler will at least help you to see where memory is allocated and if memory allocation is an issue in your application. This is often more useful than the actual object size.

Mikael Svenson
A: 

I wonder how System.Runtime.InteropServices.Marshal.SizeOf() works? There are a lot of interesting static functions under the Marshal object that might be helpful here.

jalexiou
That cake is a lie too.
Hans Passant
Intriguing ... I'll try it out!
Jeffrey Cameron