tags:

views:

31

answers:

1

Hi
I want to know, when i cache a class with no parameters of fields, how much space it takes ? Is it true that only fields and properties of a class consume space ? if it is true, when i create a class with this specification is it true that it occupies only pointer to this class in cache ? Please help me with how caching really works in terms of occupy space of a class element

A: 

An "empty" object (var obj = new object();) occupies 12 bytes (I previously had said 16 bytes) in the 32 bit runtime. It occupies 24 bytes in the 64 bit runtime.

Here's the program I use to test that.

        var objs = new List<object>(1000000);
        var memUsedStart = GC.GetTotalMemory(true);
        Console.WriteLine("Beginning memory usage = {0:N0}", memUsedStart);
        for (int i = 0; i < 1000000; ++i)
        {
            objs.Add(new object());
        }
        var memUsedEnd = GC.GetTotalMemory(true);
        Console.WriteLine("{0:N0} items in list", objs.Count);
        Console.WriteLine("Ending memory usage = {0:N0}", memUsedEnd);
        var memUsed = memUsedEnd - memUsedStart;
        Console.WriteLine("Difference = {0:N0}", memUsed);
        Console.WriteLine("Bytes per object = {0}", memUsed / 1000000);
        Console.ReadLine();
Jim Mischel
do you have some sources like msdn?
cevik
how did you get these numbers ?
Ehsan
I got those numbers by allocating a million objects and comparing the ending memory usage against the starting memory usage. I don't recall MSDN having any information about it, but it's been noted by a number of people over the years, including me in my .NET Reference Guide. Another mention: http://www.simple-talk.com/dotnet/.net-framework/object-overhead-the-hidden-.net-memory--allocation-cost/.
Jim Mischel
Interesting. I just answered [this SO question](http://stackoverflow.com/questions/3815227) and would have expected that an object with no fields would take 8 (x86) or 16 (x64) bytes. Where do the additional 8 bytes come from?
dtb
[Teh Skeet says](http://stackoverflow.com/questions/520922) it's 12 bytes in the 32-bit runtime.
dtb
@dtb: the extra 8 bytes is probably allocation overhead in the runtime, not actually on the object.
Jim Mischel
I got 24bytes per object in my test with this sample under W7 x64...
cevik