Generations of Garbage Collector

Memory management is the main concern for any application whether application is window based or web based. In .Net, CLR has garbage collector that executes as a part of our program and responsible for reclaiming the memory of no longer used objects. Garbage collector(GC) free the memory for objects that are no longer referenced and keeps the memory for future allocations.

 
While memory allocation on the managed heap is fast, GC itself may take some time. With this in mind several optimizations have been made to improve performance.

The GC supports the concept of generations, based on the assumption that the longer an object has been on the heap, the longer it will probably stay there. When an object is allocated on the heap it belongs in generation 0. Each garbage collection that object survives increases its generation by 1 (currently the highest supported generation is 2).

Obviously it’s faster to search through, and garbage collect a subset of all objects on the heap, so the GC has the option of collecting only generation 0, 1 or 2 objects (or whatever combination it chooses until it has sufficient memory). Even while collecting only younger objects the GC can also determine if old objects have references to new objects to ensure that it doesn’t inadvertently ignore in-use objects.

Generation 0

This is the youngest generation and contains the newly created objects. Generation 0 has short-lived objects and collected frequently. The objects that survive the Generation 0 are promoted to Generation 1.
Example : A temporary object.

Generation 1

This generation contains the longer lived objects that are promoted from generation 0. The objects that survive the Generation 1 are promoted to Generation 2. Basically this generation serves as a buffer between short-lived objects and longest-lived objects.

Generation 2

This generation contains the longest lived objects that are promoted from generation 1 and collected infrequently.
Example : An object at application level that contains static data which is available for the duration of the process.

Garbage Collector Working Phase

Marking Phase – In this phase garbage collector finds and creates a list of all live objects.
Relocating Phase – In this phase garbage collector updates the references to the objects that will be compacted.
Compacting Phase – In this phase garbage collector reclaims the memory occupied by the dead objects and compacts the surviving objects. The compacting phase moves the surviving objects toward the older end of the memory segment.