Skip to content

Instantly share code, notes, and snippets.

@breezhang
Created February 1, 2014 07:01
Show Gist options
  • Save breezhang/8749054 to your computer and use it in GitHub Desktop.
Save breezhang/8749054 to your computer and use it in GitHub Desktop.
get size of a managed object 85k? ...

There is no real way to know how much memory the object is using. The hashtable itself takes up some space. Each key will take up additional space (not part of the hashtable) and each value has its own set of space. If any of these have children then the children are separate as well.

The sizeof keyword in C# can be used to find the size of any value type but requires the use of unsafe code for anything other than PoDs. The Marshal.SizeOf method can be used to calculate the unmanaged size of an object but it will not handle the various subobjects mentioned earlier. The only way to determine the actual memory used would be to walk every object and every child object referenced. An alternative would be to serialize the binary object out to a binary formatter. This would give you a close approximation of the binary size but not necessarily the actual memory size.

You can use a profiler to get a better idea of the memory usage of an object but you can't do this programmatically very easily.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment