Pages

Wednesday, June 17, 2009

Stack VS Heap

Why structures are more efficient than classes?

Structures are value types and classes are reference types. Value types store data in the stack where as reference types store data in the heap (They store a pointer to that data in stack)

Stack

It works in LIFO order.
Static memory allocation
Each thread gets a stack
The size of stack is decided when the thread is created (It is limited)
Stack is faster as the way data is stored is simple and it is easy to access data in a sequence.
Each byte in the stack tends to be reused very frequently which means it tends to be mapped to the processor's cache, making it very fast.
Stack is better if you know how much data you are going to store at the runtime and if it is a small amount. (Too much data will cause stack overflow)
Variables created in stack can go out of scope and memory is de allocated.
The best thing about stack is you don’t have to worry about garbage collection.
Stack is more expensive, yet faster.


Heap

Dynamic memory allocation.
There is no exact patter or order in allocating memory. It is arbitrary.
There’s only one heap for the application.
The size of heap is decided in application start up but can enhance in need.
Heap has more complex way of allocating and accessing memory.
Variables in heap should be removed manually as they do not go out of scope.
When you use the “new” keyword the memory is allocated in heap.
The size of memory allocated in heap is not known to the compiler so that programmer has to assign and release it manually. (Now some languages provide this functionality as well still this is considered as a performance issue)

No comments:

Post a Comment