What is the memory overhead of a .NET Object
Asked Answered
S

1

53

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?

Sandysandye answered 18/5, 2012 at 15:51 Comment(7)
Heap and stack are implementation details.Llewellyn
@ThePower: Not a duplicate. That other question (and its answers) don't talk about the basic memory overhead of a .NET object at all.Connally
@ThePower It doesn't answer my question, I want to know the memory overhead, not how to measure itSandysandye
@Llewellyn - could you explain your comment? I thought a heap was an abstract data structure in which all objects are stored... why is it wrong to ask "How much space does it occupy in the heap"?Sandysandye
How does: "You could use a memory profiler like .NET Memory Profiler...." answer my question????Sandysandye
@reach4thelasers: Why can't you just measure it to find out?Pinnatisect
@Sandysandye blogs.msdn.com/b/ericlippert/archive/2009/04/27/…Llewellyn
M
62

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.)

Madelenemadelin answered 18/5, 2012 at 15:54 Comment(4)
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.Singsong
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.Acaroid
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 youRutherfordium
@BorisD: Yes - it's the memory required in addition to the "obvious" memory required for the data itself. (Housekeeping information etc.)Madelenemadelin

© 2022 - 2024 — McMap. All rights reserved.