Size of object in at runtime memory

  • Thread starter Thread starter Rune Andersen
  • Start date Start date
R

Rune Andersen

Hi....

I'm working on a cache controller and needs to know the current size of the
cache object, but how do I get that ?

I've got an ArrayList populated with structs and now I want to know the
current memory usage of the ArrayList at runtime.

I've tried using

System.Runtime.InteropServices.Marshal.SizeOf( object structure );

but it seems like it's only working on types like int, long, double etc.

Is there any method I can use that gives me the size of memory used by a
specified object ?


/Rune
 
Hi Rune,

Normally you cannot get the size of an object in the managed heap. This is
because that size doesn't make sense in the managed world due to different
reasons. One of them could be that the size of the same object is not
guaranteed to be the same between two starts of the application. The JIT
compiler is free to layout the objects as it sees fit. The layouting can be
different due to different configuration of the machine, different version
of the CLR, etc.
Furthermore, your type may reference other reference types. Even two objects
can cross-reference the same object. How can you possibly tell what is the
size of the object

Using Marshal.SizeOf returns the size of the marshaled (unmanaged)
equivalent of the provided type.

I said "normally" back then because there is an operator that returns the
managed size for a type (only for valuetypes). In C# it is represented by
the *sizeof* operator. However *sizeof* operator has some limitations in
addition to its syntax I don't think that is what you need.

About sizeof operator you can read at MSDN
ms-help://MS.MSDNQTR.2003FEB.1033/csref/html/vclrfSizeofPG.htm

To demonstrate the difference between Marshal.SizeOf and *sizeof* operator
run the following simple code

class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
unsafe static void Main(string[] args)
{

Console.WriteLine("Managed size: {0}", sizeof(char));
Console.WriteLine("Unmanaged size: {0}", Marshal.SizeOf(typeof(char)));
Console.ReadLine();
}
}

The result is:
Managed size: 2
Unmanaged size: 1

Unmanaged size is 1 because System.Char struct is set to be marshaled as
ANSI char by default.
 
Back
Top