Garbage Collection
Garbage Collection
Generations:
GC supports the concept of generations. It helps to organize short-lived and long-lived objects
in a managed heap.
1. Generation 0
2. Generation 1
3. Generation 2
1. Generation 0:
When an object is allocated on the Heap, it belongs to generation 0. It is the young
generation, which contains short-lived objects like temporary variables. If newly
allocated objects are larger in size, they will go on the large object heap in a generation
2 collection. GC occurs mostly in generation 0.
2. Generation 1:
When objects survive from a garbage collection of generation 0, they go to generation
1. Objects in generation 1 serve as a buffer between short-lived and long-lived objects.
3. Generation 2:
When objects survive from a garbage collection of generation 1, they go to generation
2. Objects in generation 2 serve as long-lived objects. If objects still survived in
generation 2, they remain in generation 2 till they’re alive.
1. Suspend all managed threads except for the thread that triggered the garbage collection.
4. Compact the survived objects and promote them to an older (higher) generation.
How the garbage collector determines when an object is no longer needed. To understand the
details, you need to be aware of the notion of application roots. Simply put, a root is a storage
location containing a reference to an object on the managed heap. Strictly speaking, a root can
fall into any of the following categories:
References to global objects (though these are not allowed in C#, CIL code does permit
allocation of global objects).