52

What is the memory overhead of an Object in .NET? I'm talking about an arbitrary bare-bones object.... the overhead of the internal .NET workings or references:

var obj = new System.Object();

How much space does obj occupy in the heap?

reach4thelasers
  • 26,181
  • 22
  • 92
  • 123

1 Answers1

61

I talk about this in a blog post "Of memory and strings". It's implementation-specific, but for the Microsoft .NET CLR v4, the x86 CLR has a per-object overhead of 8 bytes, and the x64 CLR has a per-object overhead of 16 bytes.

However, there are minimum sizes of 12 and 24 bytes respectively - it's just that you get the first 4 or 8 bytes "free" when you start storing useful information :)

(See the blog post for more information.)

smith324
  • 13,020
  • 9
  • 37
  • 58
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 2
    There may be padding for member variables to fit on address boundaries as well. This padding concept further complicates the calculation of memory overhead of an object. No wonder C# never introduced sizeof operator for instance variables for types. – RBT Aug 16 '16 at 09:13
  • 1
    I ran a few tests in a .net console app to check memory usage. Creating 10 million empty objects resulted in ca 340MB usage (includes the list with references). Adding 1 or 2 integers to the class changed nothing. Only when adding the 3rd integer did I see an increase to ca 430MB. This fully supports your statement of 24 bytes minimum with 8 bytes free for information. – JohnF May 04 '20 at 16:13
  • Hi @JonSkeet could you add a generic definition for "memory overhead"? I dont really understand what it is. It's like an extra memory allocated for each object? Thank you – BorisD Feb 01 '22 at 15:32
  • @BorisD: Yes - it's the memory required in addition to the "obvious" memory required for the data itself. (Housekeeping information etc.) – Jon Skeet Feb 01 '22 at 16:12