.Net Garbage Collection in depth

.Net Garbage Collection in depth

14 Aug 2025
Advanced
115K Views
16 min read
Learn with an interactive course and practical hands-on labs

Free ASP.NET Core Online Course with Certificate - Start Now

.NET Garbage Collection is a memory management process that automatically reclaims unused memory, ensuring efficient use of system resources and preventing memory leaks. Memory management is the main concern for any application whether application is window based or web based. 

In this .NET tutorial, you will able to learn about garbage collection, key features about garbage collection, memory alloction, key points of garbage collector, generations of .net garbage collection, how garbage collection works and more on. Let's dive in!

What Is Garbage Collection?

Garbage Collection in .NET is an automatic memory management system that efficiently reclaims unused memory, prevents leaks, and improves application performance. Garbage collection (GC) is a fundamental aspect of memory management in modern programming languages like C#. 

When objects are created in a .NET application, they are stored in the managed heap. Over time, some of these objects become unreachable (no longer needed). The Garbage Collector (GC) automatically identifies and removes these objects to free memory. Garbage collector free the memory for objects that are no longer referenced and keeps the memory for future allocations.

Key Features of Garbage Collector

Automatic Memory Management

  • Frees developers from manually allocating and deallocating memory.
  • Ensures that memory is released once objects are no longer needed.

Prevent Memory Leaks

  • Identifies and removes unreachable or unused objects from memory.
  • Helps maintain the health and stability of long-running applications.

Optimize Application Performance

  • Reclaims memory efficiently to make space for new object creation.
  • Reduces the risk of out-of-memory errors and excessive memory usage.

Improve Developer Productivity

  • Allows developers to focus on business logic rather than memory management.
  • Reduces errors related to manual memory handling like dangling pointers or double frees.

Manage Object Lifetime

  • Tracks the lifetime of objects and automatically disposes of those that are no longer in use.

Ensure System Stability and Scalability

  • Helps applications run reliably over time, especially important in web servers, services, and enterprise apps.

Support Multithreaded Environments

  • Garbage Collector is thread-safe and works well in multi-core and server-side environments.

    Memory Allocation in Managed Heap

    The managed heap is a series of allocated memory segments (approx 16Mb in size each) to store and manage objects. By taking Dot Net Training you will understand the memory for newly created object is allocated at the next available location on the managed heap. If there is available free memory, the garbage collector doesn't search the dead objects for memory reclaim and memory allocations has been done very fast. If the memory is insufficient to create the object, the garbage collector search the dead objects for memory reclaim for the newly object.

    Memory Allocation in Managed Heap

    An object is created using the new operator. This operator first makes sure that the bytes required by the new object fit in the reserved region (committing storage if necessary). If the object fits, NextObjPtr points to the object in the heap and object's constructor is called and the new operator returns the address of the object.

    Key points about Garbage Collector

    1. Contiguous Heap Allocation: All objects in the heap are allocated from one contiguous range of memory address and heap is divided into generations so that it is easy to eliminate the garbage objects by looking at only a small fraction of the heap.

    2. Generational Design: The heap is divided into generations: Gen 0, Gen 1, Gen 2, and the Large Object Heap (LOH). Gen 0 and Gen 1 occupy a single segment known as the ephemeral segment. Gen 2 is a set of further segments and the large object heap is yet another group of segments.

    3. Object Ageing: Almost, all objects with-in a generation are of the same age. 

    4. Memory Address Ordering: newest objects are created at higher memory address while oldest memory objects are at lowest memory address with in the heap. The allocation pointer for the new objects marks the boundary between the allocated and free memory.

    5. Heap Compaction: Periodically the heap is compacted by removing the dead objects and sliding up the live objects towards the lower memory address end of the heap as shown in above fig.

    6. Object Order Is Preserved: The order of objects (after memory reclaims) in memory remains the same as they were created. There are never any gaps among the objects in the heap.

    7. Memory Commitment: Only some of the free memory is committed when required and more memory is acquired from the OS in the reserved address range.

    Generations in .NET GC

    The managed heap is organized into three generations and LOH (for Large Object Heap) so that it can handle short lived and long lived objects efficiently. Garbage collector first reclaim the short lived objects that occupy a small part of the heap.

    Generations in Managed Heap

    Generation 0

    This is the youngest generation and contains the newly created objects. Generation 0 has short-lived objects and collected frequently. The objects that survive the Generation 0 are promoted to Generation 

    Example : A temporary object.

    Generation 1

    This generation contains the longer lived objects that are promoted from generation 0. The objects that survive the Generation 1 are promoted to Generation 2. Basically this generation serves as a buffer between short-lived objects and longest-lived objects.

    Generation 2

    This generation contains the longest lived objects that are promoted from generation 1 and collected infrequently.

    Example : An object at application level that contains static data which is available for the duration of the process.

    LOH (Large Object Heap) 

    Used for For large objects. Allocates objects > 85,000 bytes (e.g., large arrays, images, video buffers). LOH is not compacted by default (unless explicitly enabled in .NET 4.5+). Collected only during Gen 2 collection. 

    How Garbage Collection Works

    The .NET Garbage Collector (GC) is a managed memory system that automatically reclaims memory occupied by unused (unreachable) objects. This allows developers to focus on building applications rather than managing memory manually.

    1. Marking Phase (Identification)

    In this phase garbage collector finds and creates a list of all live objects.

    • It starts from the root references (e.g., local variables, static fields, CPU registers).
    • Then it traces all objects reachable from those roots.
    • Unreachable objects are considered garbage.

    2. Relocating Phase

    In this phase garbage collector updates the references to the objects that will be compacted. 

    3. Compacting Phase

    In this phase garbage collector reclaims the memory occupied by the dead objects and compacts the surviving objects. The compacting phase moves the surviving objects toward the older end of the memory segment.

    1. Compacting Phase

    Note

    The large object heap is not compacted, because copying large objects imposes a performance penalty.

    Garbage Collection Algorithm

    Garbage collector determine whether any object in the heap is dead or not being used by the application. If such objects exist then memory used by these objects can be reclaimed. But how garbage collector know about these objects?

    Each and every application has a set of roots and these identify the storage locations for the objects on the managed heap.

    Example : All the global, static objects pointers and all the local variable/ parameter object pointers on the thread's stack in the application are considered part of the application's roots. More over any CPU registers containing pointers to objects in the managed heap are also considered a part of the application's roots.

    The list of active roots is maintained by the JIT compiler and CLR, and is made accessible to the garbage collector's algorithm.

    Memory Reclaim Process

    Now the garbage collector starts go through the roots and make a graph of all the objects reachable from the roots. The below fig. shows a heap with allocated objects. In this heap the application roots directly refer to the objects 1,3,4,6 and object 3 & 6 refers to the objects 8 & 10. Hence all these objects will become the part of the live objects graph.

    Memory Reclaim Process

    The objects which are not reachable from application's roots, are considered as garbage since these are not accessible by the application. In above heap objects 2,5,7,9 will be considered as dead objects.

    Memory Reclaim Process

    The garbage collector then remove the dead objects from the heap and live objects will move toward the older end of the memory segment as shown in below fig. Garbage collector also updates all the references(including root references) to the moving objects in the heap.

    Memory Reclaim Process

    Reference : https://learn.microsoft.com/en-us/archive/msdn-magazine/2000/november/garbage-collection-automatic-memory-management-in-the-microsoft-net-framework 

    Conclusion

    Garbage Collection (GC) in .NET is a cornerstone of the Common Language Runtime (CLR), enabling automatic and efficient memory management. It simplifies development by relieving developers from manual memory allocation and deallocation, thus reducing common programming errors like memory leaks, dangling pointers, and fragmentation.

    To make things easier for you, Dot Net Tricks brings a comprehensive skill-oriented Dot Net Certification to the nitty-gritty of the .NET.

    FAQs

    . NET's garbage collector manages the allocation and release of memory for your application. Each time you create a new object, the common language runtime allocates memory for the object from the managed heap.

    NET GC uses a generational approach to improve efficiency, dividing the heap into three generations:
    1. Generation 0: Short-lived objects. Most objects are reclaimed for garbage collection here.
    2. Generation 1: Serves as a buffer between short-lived objects and long-lived objects.
    3. Generation 2: Long-lived objects.

    Prevents memory leaks: Garbage collection helps prevent memory leaks, which can occur when a program does not release memory that is no longer needed. This can cause the program to consume more memory than necessary, leading to slow performance, and eventually crashing.

    Take our Net skill challenge to evaluate yourself!

    In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

    GET FREE CHALLENGE

    Share Article
    About Author
    Shailendra Chauhan (Microsoft MVP, Founder & CEO at ScholarHat)

    Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

    Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
    Live Training - Book Free Demo
    Azure AI & Gen AI Engineer Certification Training Program
    28 Aug
    08:30PM - 10:30PM IST
    Checkmark Icon
    Get Job-Ready
    Certification
    .NET Solution Architect Certification Training
    30 Aug
    10:00AM - 12:00PM IST
    Checkmark Icon
    Get Job-Ready
    Certification
    Software Architecture and Design Training
    30 Aug
    10:00AM - 12:00PM IST
    Checkmark Icon
    Get Job-Ready
    Certification
    Advanced Full-Stack .NET Developer with Gen AI Certification Training
    31 Aug
    08:30PM - 10:30PM IST
    Checkmark Icon
    Get Job-Ready
    Certification
    ASP.NET Core Certification Training
    31 Aug
    08:30PM - 10:30PM IST
    Checkmark Icon
    Get Job-Ready
    Certification
    Accept cookies & close this