Garbage Collection in C#

Garbage Collector is an automatic memory manager. It frees the memory occupied by objects which are no longer in use by the application. It works well in the managed heap.

Let us discuss in detail about the Garbage Collector.

We know that each time a new variable is created, memory is allocated from the managed heap by the CLR. As memory is not infinite, so there required a method to free memory occupied by unreachable objects or that are no longer being used by the application. So here comes the role of Garbage Collector’ it also checks for the fragmentation problems. Click here



When Garbage Collector is called ?

    • Whenever the physical memory is getting low
    • Whenever the memory allocated to the objects in the managed heap surpasses the threshold it runs and adjusted as the process runs.

(Threshold is the magnitude or intensity set that must be exceeded for the GC to run.)

  • When GC.Collect() is called. It is called internally in almost all cases.

Fundamentals of Memory

Garbage Collector

In a computer all processes share the same physical memory but all are having their own seperate virtual address space. GC works with this virtual space and we also work only with this virtual memory not directly with physical memory.

This memory is divided into 3 parts:

  • Free
  • Reserved
  • Committed

Memory Fragmentation

This memory is also get fragmented. Means you have free space (holes) in memory that is needed for the coming request but still memory low error occurs.

Explaination
Whenever any request comes for memory allocation it searches for a single block of free space.
Garbage Collector

Suppose a request of 3GB comes we have enough space in memory but that is fragmented so even when we have space the coming request is unsuccessful. This is the fragmentation problem. Garbage Collector also take care of this problem.

The memory managed scenario in heap is organised in generations. Typically 3 Generations are there.