Lets Learn about the garbage collector in dotnet .Garbage Collection is a technique that manages memory automatically .
Collection is a technique that manages
memory automatically. In C
and C++ we need to cleanup the heap memory explicitly using
a free function of C and delete operator of C++. In Dotnet, The
Common Language Runtime (CLR) requires that you create objects in the
managed heap, but you do not have to bother with cleaning up the
memory once the object goes out of the scope or is no longer needed.
The objective of this article is to know how the garbage collector in .NET works and to know about the generations in the Garbage Collector.
Phases in GC
They are three important phases in GC.
2)Relocating Phase 3)Compacting Phase
that are not reachable from the root are referred to as garbage
objects and are marked for garbage collection.
Generations in GC functionality
Generation 0 :
This is the youngest
generation and contains short-lived objects. An example of a
short-lived object is a temporary variable. Garbage collection occurs
most frequently in this generation.Most objects are reclaimed for garbage
collection in generation 0 and do not survive to the next generation.
Generation 1 :
This generation contains short-lived
objects and serves as a buffer between short-lived objects and
long-lived objects.GC is performed. This time, all objects in generation 1 that survive are compacted and considered to be in generation 2 . All survivors in generation 0 are now compacted and considered to be in generation 1. Generation 0 currently contains no objects, but all new objects will go into generation 0.
Generation 2 :
This generation contains long-lived
objects. Garbage collections occur on specific
generations as conditions warrant. Collecting a generation means
collecting objects in that generation and all its younger
generations. A generation 2 garbage collection is also known as a
full garbage collection, because it reclaims all objects in all
GC functionality :
When ever a new object is created then it will be moved into the Generation 0.when Generation 0 is filled then the GC will run and compact all the objects that have scope to next Generation i.e Generation 1.Even if Generation 1 is filled then it will compact the objects that have scope to the next generation i.e Generation 2.
All the new objects are created in the Generation 0.
We checked how Garbage Collector in Dotnet performs memory management. In the next article we will learn about the inbuilt functionalities of Garbage Collector .Thanks to Jeffrey Richter for his Paper presentation on Garbage Collector