Object size in memory c#
15/01/2010 Leave a comment
Unfortunately there is no direct way to do it. Speacialy for the managed code. May you can use memorystream and serialization for getting an idea but this are not actual size of your object. You may use some solution below for calculation actual size.
One way is to use the GC.GetTotalMemory method to measure the amount of memory used before and after creating your object. This won’t be perfect, but as long as you control the rest of the application you may get the information you are interested in.
Using Strike or SOS Debugging Extension (SOS.dll)
use : DumpHeap [-stat] [-min <size>][-max <size>] [-thinlock] [-mt <MethodTable address>] [-type <partial type name>][start [end]]
Displays information about the garbage-collected heap and collection statistics about objects.
The DumpHeap command displays a warning if it detects excessive fragmentation in the garbage collector heap.
The -stat option restricts the output to the statistical type summary.
The -min option ignores objects that are less than the size parameter, specified in bytes.
The -max option ignores objects that are larger than the size parameter, specified in bytes.
The -thinlock option reports ThinLocks. For more information, see the SyncBlk command.
The -mt option lists only those objects that correspond to specified the MethodTable structure.
The -type option lists only those objects whose type name is a substring match of the specified string.
The start parameter begins listing from the specified address.
The end parameter stops listing at the specified address.
Note that !dumpheap only gives you the bytes of the object type itself, and doesn’t include the bytes of any other object types that it might reference
3rd party solutions
Using .Net Memory Profiler (Easy way)
ANTS Memory Profiler
Some people have confused the System.Runtime.InteropServices.Marshal.SizeOf() service with this API. However, Marshal.SizeOf reveals the size of an object after it has been marshaled. In other words, it yields the size of the object when converted to an unmanaged representation. These sizes will certainly differ if the CLR’s loader has re-ordered small fields so they can be packed together on a tdAutoLayout type.
source : http://blogs.msdn.com/cbrumme/archive/2003/04/15/51326.aspx