Garbage Collection in C#

Why Garbage Collection is needed ?

When you create any object in C#, CLR (common language runtime) allocates memory for the object from heap. This process is repeated for each newly created object, but there is a limitation to everything, Memory is not un-limited, and we need to clean some used space in order to make room for new objects, Here the concept of garbage collection is introduced, Garbage collector manages allocation and reclaiming of memory. GC (Garbage collector) makes a trip to the heap and collects all objects that are no longer used by the application and then makes them free from memory.

What is Garbage Collection?

  • The garbage Collection manage the allocation & release of memory.
  • When there isn't enough memory to allocate an object ,the GC(garbage collector) must collect and dispose of garbage memory to take the memory available for new allocations. This process is known as garbage collection.
  • GC allocates the memory in Heap memory. The garbage collector takes care of memory management automatically, which can help reduce the risk of memory leaks and other issues.
  • It allocate the memory for the unused objects.
  • AMM(Automatic Memory Management) is performed in the Heap memory.
  • Heap memory is divided into 3 generations.
    • Generation 0
    • Generation 1
    • Generation 2

Generation 0 Heap Memory

  1. Generation 0 is called younger generation. All the newly created object will be allocating memory into the Generation 0. All the short-lived objects such as temporary variables are contained in the generation 0 of the heap memory.
  2. If there is not sufficient memory in generation 0 then it will promote the generation o to generation 1.

Generation 1 Heap Memory

  1. If space occupied by some generation 0 objects that are not released in a garbage collection run, then these objects get moved to generation 1.
  2. This generation contains short-lived objects and serves as a buffer between short-lived objects and long-lived objects.

Generation 2 Heap Memory

  1. When there is no sufficient memory the object from the generation 1 will be promoted to the generation 2.
  2. Generation 2 will contains longest lived object such as static objects, global variables as they remain in the heap memory for the whole process duration.
  3. The memory allocated to the Generation 2 will be greater than Generation 1’s memory and similarly the memory of Generation 1 will be greater than Generation 0’s memory(Generation 2 > Generation 1 > Generation 0).

Phases in Garbage Collection

There are 3 phases in garbage collection.

1. Marking: It will create the list of live object. All of the objects that are not on the list of live objects are potentially deleted from the heap memory.

2. Relocate: It will update the reference object. The references of all the objects that were on the list of all the live objects are updated in the relocating phase so that they point to the new location where the objects will be relocated to in the compacting phase.

3. Compacting: It will clear the unused object from the memory.

Now i will demonstrate sample program for Garbage Collection build in properties & Methods.

Properties of Garbage Colllection


MaxGeneration

This property in the GC class returns the total number of generations. 

Example

using System;

public class CSharpConcept
{
    public static void Main(string[] args)
    {
        try
        {
            Console.WriteLine("Garbage Collection Maximum Generations : " + GC.MaxGeneration);
        }
        catch (Exception Ex)
        {
            Console.WriteLine(Ex.Message);
        }
    }
}

Output

maxgeneration

Explanation

In the above code we have used the built-in property i.e MaxGeneration for GC class & it will return the highest generation in the garbage collection. As we know the generation in GC class will start from Generation 0 & it will continue till generation 2. In the code it will return 2 as max generation as a output. That means we will have total 3 generation in garbage collection i.e Generation 0, Generation 1 & Generation 2.

Note.  If you will run this program on online compilers then you may get different outputs as it depends on the system.

Methods of Garbage Collection


1. GC.GetGeneration()

This method returns the generation number of the target object. It requires a single parameter i.e. the target object for which the generation number is required.

Example

using System;

public class CSharpConcept
{
    public static void Main(string[] args)
    {
        CSharpConcept objcsharp = new CSharpConcept();
        Console.WriteLine("The number of generations of object objcsharp is: " + GC.GetGeneration(objcsharp));
    }
}

Output

garbagecollection

Explanation

In the above code we have used the GetGeneration() method which will return the generation number of the target object. In the main method we have created object of the class i.e CSharpConcept & the same object i.e objcsharp will be passed as a input parameter for the GetGeneration() method. When we will execute the program will get the o/p as 0.

2. GC.Collect()

This method requires a single parameter i.e. number of the oldest generation for which garbage collection occurs.

Example

using System;

public class CSharpConcept
{
    public static void Main(string[] args)
    {
        GC.Collect(0);
        Console.WriteLine("Garbage Collection in Generation 0 is: " + GC.CollectionCount(0));
    }
}

Output

gc collect

Explanation

In the above example we have used the GC.Collect() method which forces an immediate garbage collection from generation 0 through a specified generation.

Summary

In this article we have learned what is Garbage collection, why it is used with examples.


Similar Articles