Geeks With Blogs
Ankit Agrawal

I am here to take your attention on size of .Net object when we call a service. This will help when you want to find out the size of .net object in a service call. This might happen when you face a buffer overrun problem.

While trying to debug a service call, where we suspect a buffer overrun situation, we wanted to find out the size of object being returned by a service call. However finding size of .net object is not trivial and if you thought that you can do it with sizeof(object), and then you are wrong. This will only return the size of object based on the size of each field in object that itself is based on the type of the field. This does not return the size of the object in memory with data loaded into it. 

Another option people try to use it Marshal.Sizeof(object), but this gives the size of unmanaged representation of the object and the layout in managed and unmanaged world may be very different.

Chris Brumme(earlier was in CLR Team) had written that there is no direct API in .net to provide this size and he has explained it here.

Some forums talk about using the serialization approach. So you essentially create a memory stream and then use binary formatter and serialize the object in the stream and then the size of the stream. The size thus obtained is really the serialized size not in the memory size. Why will the two differ?

These can differ for:

1. The layout of the object in memory/byte alignment etc. will cause the difference.

2. If the object overrides and custom serialization, it might after what all gets serialized and thus the size will differ.

Another option that possibly best according to me is to use GC.GetTotalMemory() API before and after the call to create the object. See details here.However this itself has its own challenges in that it is not thread safe, as the blogs also point out. Multiple things can happen between two calls to GC and other threads may release or allocate other objects and hence the size difference you will get may not truly reflect the size of only this object. Another aspect is that this object itself may need multiple steps to fully populate and hence enclosing these steps within calls to GC.GetTotalMemory() may be tricky.

There is one last option, which will be mostly 100% accurate, and this is to take the memory dump of the process once the object is allocated and then using WinDBG find out the total size of the object by using the objsize command.  See some explanation how to use WinDBG for this purpose here.


Hope it will help all of you if you have any issues related to this. 

Till next time and welcome all for your valuable comments.


Posted on Tuesday, October 11, 2011 6:34 PM | Back to top

Comments on this post: Size of object in .Net

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © AnkitAgrawal | Powered by: