views:

1665

answers:

3

Hi guys,

I was wondering if there is a way to find the size of a reference type in C#. I've done some googling and the general idea on the forums seem to be that this isn't possible. I thought I'd ask you guys and see if anyone here knew better ;) ([cough] Jon Skeet [cough])

After all, profiling tools must have a way of doing this? I know it isn't usual to need to know this information, but it would be useful to have in some situations.

A: 

A rough estimate can be done, and tracking the used memory via profilig should also be possible. But the JIT has the freedom of setting up the layout of the type as it fits best, which may also depend on framework version, machine configuration (especially 32bit vs. 64bit), framework provider (MS, Mono, GNU.NET etc.) etc.

Computing it in advance will be similar to this:

  • References are 32bit or 64bit depending on platform

  • A class instance has an internal reference to the type information (which includes VTable etc.), plus a reference for each reference type contained (including strings or arrays), plus the memory used by any structs (these may be layouted so that access is efficient, in fact leaving some memory unused).

So the question is also, do you want to get the memory used by the class or by the class and the associated data (like strings, arrays, lists, dictionatries etc. in fields)?

Lucero
A: 

Hmmm. I'd be using a profiling tool, but I guess something like this might work:

long before = System.GC.GetTotalMemory(true);
Foo instance = new Foo();
long after = System.GC.GetTotalMemory(true);
long consumed = after - before;
annakata
+1  A: 

Check this detailed answer by Jon, you'll find some useful information.

Moayad Mardini
Thank you - I was trying to find that question!
Jon Skeet
Actually that's (typically) comprehensive and the top paragraph effectively makes this question a subset. Voting to close based on this.
annakata