Sunday, July 13, 2008

Stack Vs. Heap

Both are part of the memory where our program is executing. But there is a basic difference.
Stack:
Stack is generally responsible for keeping track of what is executing in our code CURRENTLY. As in stack only the top is accessible, any thing is being executed currently (say a) is kept on the stack. If it(a) is IN SCOPE but something other(say b) need to be executed, that (b) is then placed on the top of stack and (a) comes below it. If execution is completed and we no more need (b) it is thrown away or discarded and again (a) comes on the top. If we again do not need (a) it also get discarded. In this way Stack works. One thing to remember, only those variables are kept on/in stack which are IN SCOPE. variables which are out of scope can NEVER come on/in stack. Stack is responsible for keeping value type variables. It never needs a GC to clean it up because Stack NEVER stores a reference type varibles GC is responsible for discarding of.

Heap:
Heap is generally responsible for keeping track of objects. It keeps track of out reference type variables like class, interface, delegate, object, string varibles. These variables do not store values instead stores references to value or reference to null. Any object in Heap can be accessed any point of time as opposed to Stack where only top is accessible. So there comes a need of which variables are now not referencing any thing NOT EVEN NULL!!! For this purpose there is structure of GC which runs when there comes a shortage of memory. GC just stops all the running threads and sees which objects in Heap are referencing variables in Stack or another object in Heap. All those objects referencing no where not even NULL are claimed by GC and memory is freed.

No comments: