Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory usage in .NET when creating a new class or struct

Tags:

c#

.net

memory

Int has a size of 4 bytes, if I create a new Int in my program will incresse its memory consumption by 4 bytes. Right?

But if I have this class

public class Dummy{
    private int;
}

How much memory will my new class use? Will be memory consumption be lower if it was a struct? I think that the reference itself will also consume some memory.

like image 792
Simon Edström Avatar asked Sep 13 '12 08:09

Simon Edström


2 Answers

A single reference either takes 4 bytes on 32-bit processes or 8 bytes on 64-bit processes. A reference is a standard overhead on classes (as they are reference types). Structs do not incur references (well, ignoring any potential boxing) and are the size of their content usually. I cannot remember if classes have any more overhead, don't think so.

This question delves into class vs struct (also provided in the question comments):

Does using "new" on a struct allocate it on the heap or stack?

As stated in the comments, only instances of a class will consume this reference overhead and only when there is a reference somewhere. When there are no references, the item becomes eligible for GC - I'm not sure what the size of a class is on the heap without any references, I would presume it is the size of its content.

Really, classes don't have a true "size" that you can rely on. And most importantly this shouldn't really be the deciding factor on using classes or structs (but you tend to find guidelines stating that types at or below roughly 16 bytes can be suitable structs, and above tends towards classes). For me the deciding factor is intended usage.

When talking about structs, I feel obliged to provide the following link: Why are mutable structs “evil”?

like image 73
Adam Houldsworth Avatar answered Sep 22 '22 16:09

Adam Houldsworth


A class is a reference type and is located a the heap ( and will be remove there from the garbabe collector). A struct ist value type and is stored on the stack.
In case of your example Microsoft recommends a value type (struct), because a reference type causes too much overhead.

If you're interested in this topic then take a look into the book "CLR via C#" from Jeffrey Richter.

like image 33
Bjoern Avatar answered Sep 22 '22 16:09

Bjoern