Skip to main content
.net

How .Net Garbage Collection Works?

Whenever you instantiate an object in your .net application, some memory is allocated to store that object. But at some point that object may no longer be needed by your application. If you want to reuse that memory in your application, we have to de-allocate that memory first. And this process of freeing up or de-allocating memory which is no longer needed by the application is called Garbage collection.

Garbage collection is an automatic process, when object is created then it will be placed in the Generation 0. The garbage collection uses an algorithm which checks the objects in the generation, the objects life time get over then it will be removed from the memory. The two kinds of objects. One is Live Objects and Dead Objects. The Garbage collection algorithm collects all unused objects that are dead objects in the generation. If the live objects running for long time then based on that life time it will be moved to next generation.

The object cleaning in the generation will not take place exactly after the life time over of the particular objects. It takes own time to implement the sweeping algorithm to free the spaces to the process.

When a garbage collection starts, it looks at a set of references called the ‘roots’. These are memory locations that are designated to be always reachable for some reason, and which contain references to objects created by the program. It marks these objects as ‘live’ and then looks at any objects that they reference; it marks these as being ‘live’ too. It continues in this manner, iterating through all of the objects it knows are ‘live’. It marks anything that they reference as also being used until it can find no further objects. Once all of these live objects are known, any remaining objects can be discarded and those spaces can be re-used for new objects and it squashes the memory so that the free memory is always located at the end of a heap so that allocation of new objects will be faster.

How Often Does the Garbage Collector Perform a Garbage Collection?

There are three ways a garbage collection can be triggered.

Firstly, if your system has low physical memory, this can trigger a garbage collection.

Secondly, a threshold is defined which indicates an acceptable level of memory on the heap which can be used by allocated objects. If this threshold is surpassed, then a garbage collection is triggered.

Garbage collection can also be triggered by calling the GC.Collect method.

C# program that uses GC.Collect
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GarbageCollection
{
    public class Work
    {
        public int salary;
        public int months;
        public int CalculateApproxCTC()
        {
            salary = 1025454564;
            months = 12;
            int CTC = salary * months;
            return CTC;
        }
    }
    class Program
    {
        static void Main()
        {
            long mem1 = GC.GetTotalMemory(false);
            {
                // Allocate an array and make it unreachable.
                int[] allocatespace = new int[5000000];
                int[] values = new int[50000]; // Generation 2 Example
                GC.GetGeneration(values);
                Console.WriteLine(GC.GetGeneration(values));
                GC.GetGeneration(allocatespace);
                Console.WriteLine(GC.GetGeneration(allocatespace));
                // just create an object of class and do not use - will be cleared by Garbage    Collection
                Work wrk = new Work();
                Console.WriteLine(GC.GetGeneration(wrk)); // Generation 0 example 
                values = null;
            }
            long mem2 = GC.GetTotalMemory(false);
            {
                // Forces an immediate garbage collection of all generations.
                GC.Collect();
            }
            long mem3 = GC.GetTotalMemory(false);
            {
                Console.WriteLine(mem1);
                Console.WriteLine(mem2);
                Console.WriteLine(mem3);
                Console.ReadLine();
            }
        }
    }
}

Output

shruthi1

 

Shruthi T

Shruthi T

Shruthi works as Senior Software Engineer with Trigent Software. With over 5 years experience, Shruthi has worked on web applications development. Her areas of expertise include C#.Net, ASP.Net, MVC ,JavaScript, JQuery.

3 thoughts on “How .Net Garbage Collection Works?

  1. I just like the valuable info you provide in your articles. I’ll bookmark your weblog and check once more right here regularly. I am reasonably certain I will learn plenty of new stuff proper right here! Best of luck for the following!

Comments are closed.