What is Garbage Collector in .Net ?

Introduction

In this article, we will discuss what is ‘Grabage collector’? and how it works in .net framework.

The one of the most important feature provided by CLR(Common Language Runtime) is Garbage collector.

When creating Desktop application or web application memory is most important concern. So Garbage collector deals with memory management in .Net and It is also called as AMM (automatic memory management).

We can clear a memory in .Net using 2 ways,

  1. Manual : Time consuming and error prone
  2. Automatic : Recommended

Following are some benefits of garbage collector

  1. Programmer / Developer no need to worry about the memory.
  2. GC allocates memory for the objects on heap memory very efficiently
  3. Deallocates memory from the unused objects

How GC Works?

In C# when we create new object, memory allocates for that object in heap and this process keeps on repeating for each object, you have created. But we have limited memory so in order to make space for newly created objects GC deletes unused objects from heap with the help of 3 generations.

Generation 0 – Whenever a new object is created using new operator then it is allocated on generation 0. Generation 0 is the youngest generation which contains the newly created objects. Basically, they are short-lived objects. The objects which survive in the generation 0 promoted to generation 1.

Generation 1 – Contains long-lived objects, When generation 0 does not have sufficient memory then we promoted generation 0 objects to generation 1. Also, generation 1 acts as a buffer for generation 0 and generation 2.

Generation 2 – when we do not have sufficient memory then objects from generation 1 is promoted to generation 2. It contains longest-lived objects. e.g – global variable, that needs to be persisted for a certain amount of time

Note : GC Gets Triggered when virtual memory is running out of space.

Leave a Comment