Size of a .net object
Another option people try to use is Marshal.Sizeof(object), but this gives the size of the unmanaged representation of the object and the layout in managed and unmanaged world may be very different.
Chris Brumme (earlier was in the 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 a serialization approach. So you essentially create a memory stream and then use binary formatter and serialize the object in the stream and then get the size of the stream. While this can be used, be aware of potential pitfall. The size thus obtained is really the serialized size and not the in-memory size. Why will the two differ? These can differ for
- The layout of the object in memory/byte alignment etc will cause the diference and
- If the object overrides and has custom serialiation, it might alter what all get's serialized and thus the size will differ.
Another option, that possibly is the 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 this isn't thread safe, as the blog also points out. Multiple things can happen between the two calls to GC and other threads may release or allocate other objects and hence the size difference you will get may not truely 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 mostly be 100% accurate, and that is to take a 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 explaination of how to use WinDBG for this purpose here.