Garbage Collection Definition
The term “Garbage collection” can be defined as management of the allocation and release of memory in an application. Garbage collection is the mechanism to manage the memory by clearing up the memory allocated for unused objects in the application.
Garbage collection is the process of removing unused objects and resources from memory when they are no longer used in the application. Visual Studio.Net automatically processes this. We can also do it within the scope if resources are not required.
Description:
Every time you create a new object, the CLR (common language runtime) allocates memory for the object in the managed heap memory. CLR allocates space for a new object until the free spaces are available in heap.
Memory is finite, so the garbage collector must collect the out of scope objects to free up some memory. The garbage collector's optimizing engine finds the best time to perform a collection based upon the memory allocations in the application. After the garbage collector performs a collection it checks for objects in the managed heap that are no longer being used by the application and performs the necessary operations to reclaim their memory.
Garbage Collection in Different Environments
C++ does not have any garbage collection mechanism, so the developers have to manually clean the memory by using the malloc(), calloc(), and free() functions.
COM (Component Object Model) introduced a new model for memory management. It’s called “Reference counting”. Developers take responsibility for incrementing the reference count when the object is used in the application and decrementing the counter when the object goes out of scope. When the object's reference count reaches zero, the object is deleted.
Java and Visual Basic have garbage collection mechanisms and perform automatic garbage collection. However, in Java the garbage collection process starts automatically after giving prior notification to the user.
Garbage Collection in the .NET Environment:
In the .NET Framework, the garbage collector is responsible for memory management. It is implemented as a separate thread, and will always be running at the back end. It also causes overhead to the memory, so low priority is assigned to this thread in order to reduce the system overhead.
When a new object needs to be instantiated, and if there is not enough room in the application’s managed heap, the garbage collection process starts.
For automatic memory management, the Garbage Collector (GC) has to know when an object is no longer in use by the application. The GC gets its information from the Meta data. Meta data is nothing more than the “Data about Data”. All data used in .NET includes Meta data. With the help of Meta data, the CLR knows the layout of all objects in memory, which helps the Garbage Collector in the compaction phase of garbage collection.
Garbage Collection Algorithm
According to the Mark and Compact algorithm, garbage collection performs the memory management in the .NET Framework. The algorithm clears the memory of objects, which are no longer in use and compact all the remaining objects at the beginning of the address space.
The garbage collection process is done in three phases.

The Three Phases are
- Mark
- Relocating
- Compact
Phase I: Mark
The Mark Phase finds and creates the list of all of the living objects and clears the remaining objects (garbage).
Phase I includes the following steps:
- Finds the application root.
- Scans the heap and finds the living objects in the heap and put into the graph.
- Frees the memory of objects that are not in the graph
After checking all of the objects, the garbage collector's graph contains a list of all living objects that are accessible by the application. The remaining objects in the application that are not in the graph are marked as garbage and cleared.
Phase II: Relocating
The relocating phase updates the reference to the object that will be compacted
Phase II includes following steps
- Due to Shifting of objects in the memory location, the pointer becomes invalid. The garbage collector has to modify the object references, to point the pointers to the object’s new location.
- If any object contains a pointer of another object, the garbage collector is responsible for correcting these pointers as well.
Phase III: Compact
The Compact phase moves all the living objects to the bottom of the heap, leaving free space at the top.
Phase III includes the following steps
- The garbage collector scans the heap and looks for free space.
- Garbage collector shifts the non-garbage (living) objects down in memory, and maintains all free spaces at the top of the heap.
After all the garbage has been cleared, the non-garbage has to be compacted, and all the living object pointers have been fixed-up. Now the pointer is positioned just after the last living object to indicate the position where the next object should be added.
Programmatically Invoking the Garbage Collector
In applications with significant memory requirements, you can force garbage collection by invoking the GC.Collect() method from the program. This is not recommended and should be used only in extreme cases. The System.GC class provides methods that control the system garbage collector.
class Account
{
public Account(string accountNumber)
{
this.accountNumber = accountNumber;
Console.WriteLine("Account::Acount - c'tor");
}
~Account()
{
Console.WriteLine("Account::~Acount - d'tor");
} protected string accountNumber;
override public string ToString() { return accountNumber; }
};
class Class1
{
[STAThread]
static void Main(string[] args)
{
CreateAccount("111006116");
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine("Application ending");
Console.ReadLine();
}
public static void CreateAccount(string accountNumber)
{
Console.WriteLine("CreateAccount - instantiate Account object");
Account account = new Account(accountNumber);
Console.WriteLine("CreateAccount - created account number {0}",account);
}
}
OUTPUT
CreateAccount - instantiate Account object
Account::Acount - c'tor
CreateAccount - created account number 111006116
Account::~Acount - d'tor
Application ending