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
Asked
Active
Viewed 221 times
2

Ehsan
- 1,662
- 6
- 28
- 49
1 Answers
1
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
- 131,090
- 20
- 188
- 351
-
3do you have some sources like msdn? – Aykut Çevik Sep 28 '10 at 17:15
-
2how did you get these numbers ? – Ehsan Sep 28 '10 at 17:20
-
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 Sep 28 '10 at 17:33
-
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 Sep 28 '10 at 17:50
-
[Teh Skeet says](http://stackoverflow.com/questions/520922) it's 12 bytes in the 32-bit runtime. – dtb Sep 28 '10 at 18:01
-
@dtb: the extra 8 bytes is probably allocation overhead in the runtime, not actually on the object. – Jim Mischel Sep 28 '10 at 18:17