Heap versus Stack allocation implications (.NET)

So long as you know what the semantics are, the only consequences of stack vs heap are in terms of making sure you don’t overflow the stack, and being aware that there’s a cost associated with garbage collecting the heap.

For instance, the JIT could notice that a newly created object was never used outside the current method (the reference could never escape elsewhere) and allocate it on the stack. It doesn’t do that at the moment, but it would be a legal thing to do.

Likewise the C# compiler could decide to allocate all local variables on the heap – the stack would just contain a reference to an instance of MyMethodLocalVariables and all variable access would be implemented via that. (In fact, variables captured by delegates or iterator blocks already have this sort of behaviour.)

Leave a Comment