Memory taken by an object

  • Thread starter Thread starter JezB
  • Start date Start date
J

JezB

How do I evaluate, in c#, the amount of memory taken up by any given object
?
 
Hi JezB,

Binary Serialize the object to disk.

Hope that helps,
Jan
 
int size = System.Runtime.InterpoServices.Marshal.SizeOf(object);
 
Hi Jan,

Just a note that this way you'll get an estimate and not an exact amount
(due to memory alignment and other context not serialized).
Perhaps the best way is to check it with a memory profiler..
 
How do I evaluate, in c#, the amount of memory taken up by any
given object?

Neither binary serialization nor marshalling will actually tell you
that information, and there's no way to determine it accurately, in a
guaranteed way.

However, each object has an 8 byte "overhead" plus the space taken for
its member fieds. Each reference is 4 bytes (on a 32 bit CLI), each
Int32 takes 4 bytes, etc. Where it becomes tricky is if you have
byte/short members - depending on attributes, these members may be
"packed" or not.

Don't forget though that two objects could both refer to the same third
object - you'd have to make sure you don't count that third object
twice if you're trying to sum the object sizes...

Jon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Back
Top