-1

I have the following lines of code:

SomeClass a;
SomeClass b = new SomeClass();
SomeClass c = new SomeClass()
{
    Foo="sss",
    Bar="dddd"
};

Whats the size (in memory) of the class instances a, b and c?

How much memory get assigned to each variable?

2
  • 1
    The actual variables are all the same size since they are references. And the actual objects in the heap will be the same size as well (note that the strings will be separate objects that this object has a reference two). And of course a does not actual reference any because it's null. stackoverflow.com/questions/3800882/…
    – juharr
    Commented Sep 11, 2017 at 14:56
  • And what is on the heap and what is on teh stack is actually a Framework implementation detail. As is string interning. And JiT Compiling might just disapear a because it is never used and it is dead code. So: Anything between the maximum and minimum amount possible, depending on the Runtime running it. The bigger question is: Why do you ask? What kind of micro-optimisation or faulty path are you on? Commented Sep 11, 2017 at 15:27

1 Answer 1

0

When you instantiate b and c, memory is automatically allocated, you don't have to handle it yourself. You can forget that part, that's the managed magic part, and garbage collector will take care of freeing the memory space for you, once these objects aren't needed anymore (no pointers to it...). Still, b and c take the same memory size, since it's the same type. a takes no space since it's not initialized yet.

4
  • a does take space in the stack for the actual variable, it just does not reference anything in the heap.
    – juharr
    Commented Sep 11, 2017 at 15:02
  • the c# compiler and JIT usually get rid of unused variables, removing them, thus allocating no memory right ?
    – KitAndKat
    Commented Sep 11, 2017 at 15:06
  • This is just a code snippet so there could be an if latter that does set a in which case it cannot be optimized away, but yeah it would likely compile as if a were not even there.
    – juharr
    Commented Sep 11, 2017 at 15:08
  • But that if statement might also be dead code, because a is never set. The compiler/JiT Compiler is about smart enough to catch those. Especially if 'a' is private and this is not part of a partical class. Commented Sep 11, 2017 at 15:29

Not the answer you're looking for? Browse other questions tagged or ask your own question.