What is Garbage Collector, Gen 0, 1 & 2?

Garbage Collector (GC) -Garbage Collector is a feature of CLR which cleans unused Managed objects and reclaims memory. It does not clean unmanaged objects. It’s a background thread which runs continuously.

Generation defines age of the object. There are 3 generations-

1. Gen 0: When application creates fresh objects they are marked as Gen 0.

2. Gen 1: When GC is not able to clear the objects from Gen 0 in first round it moves them to Gen 1 bucket.

3. Gen 2: When GC visits Gen 1 Objects and it is not able to clear the objects from Gen 1, it moves them to Gen 2 bucket.

Generations are created to improve GC performance. GC will spend more time on Gen 0 objects rather than Gen 1 and Gen 2 thus improving performance. More objects is in Gen 0 is good sign rather than more objects in Gen 1/ Gen 2.

We can see Generations of Garbage Collector by creating a windows application in which we will put a button and put the following code in .cs file. We will use CLR Profiler to see the Generations.

private void button1_Click(object sender, EventArgs e)

{

for(int i=0;i<1000000;i++)

{

cls obj=new cls();

}

}

}

public class cls1

{

}

CLRProfiler- CLRProfier is a tool provided by Microsoft.com. To see Generations of Garbage Collector (Gen0, 1, 2).