Friday, June 7, 2013

What is a Garbage Collector?

The Garbage Collector is a mechanism employed by the .Net runtime to manage the memory of objects added to the managed heap. Variables and references stored in a Stack Frame are cleared (popped) out once the method execution gets completed, but this is not the case for Heaps, there is no mechanism to clear the objects loaded into the Heap, this is where the Garbage collector comes into play.
The role of Garbage collector is to manage the Heap by removing objects which are not used in the Heap. The Garbage collector uses various algorithms to effectively determine and clear unused objects from the Heap.

When a new object is added to the Heap, a reference to the object (Address) is added to the stack, once the method execution gets completed the stack frame used by the method is cleared (popped out) hence the reference pointing to the object in the Heap is also removed. Now this object is an orphan it has no address. The Garbage collector identifies such orphan objects and clears them out from the Heap to free memory.

The Garbage collector does not remove orphan objects randomly from the heap; it maintains a Generation algorithm to determine objects which are not used for a long time and starts clearing the objects which are not used for a longer time.

We shall see more on the mechanism used by the Garbage collector to handle memory management of the managed heap in the following posts.

Search Flipkart Products:
Flipkart.com

No comments: