Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Heap versus Stack allocation implications (.NET)

Tags:

From an SO answer1 about Heap and Stack, it raised me a question: Why it is important to know where the variables are allocated?

At another answer someone pointed that the stack is faster. Is this the only implication? Could someone give a code example where a simple allocation location change could solve a problem (eg. performance)?

Note that this question is .NET specific

1 the question is removed from SO.

like image 857
Jader Dias Avatar asked Jan 25 '09 03:01

Jader Dias


People also ask

What is the advantage of the heap allocation method over the stack allocation?

Stack accesses local variables only while Heap allows you to access variables globally. Stack variables can't be resized whereas Heap variables can be resized. Stack memory is allocated in a contiguous block whereas Heap memory is allocated in any random order.

What is the difference between allocating objects on the stack vs the heap?

In a stack, the allocation and de-allocation are automatically done by the compiler whereas in heap, it needs to be done by the programmer manually.

Are allocations faster on stack or heap?

Because the data is added and removed in a last-in-first-out manner, stack-based memory allocation is very simple and typically much faster than heap-based memory allocation (also known as dynamic memory allocation) e.g. C's malloc .

Why use the heap instead of the stack?

Use the stack when your variable will not be used after the current function returns. Use the heap when the data in the variable is needed beyond the lifetime of the current function.


1 Answers

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

like image 159
Jon Skeet Avatar answered Oct 14 '22 19:10

Jon Skeet