Phase 24 of 30 · Topic 24.1

Generational Garbage Collection: Gen 0, Gen 1, Gen 2 & Ephemeral Segment

1Concept

The CLR GC divides the managed heap into 3 generations based on the weak generational hypothesis: newly allocated objects (Gen 0) die fast; survivors promote to Gen 1 and eventually Gen 2.

2Architecture Diagram

[ New Allocation ] ──> Gen 0 (Ephemeral: Few KB/MB, sub-millisecond sweep)
                               │ (Survives Gen 0 GC)
                               ▼
                            Gen 1 (Buffer / Short-lived survivors)
                               │ (Survives Gen 1 GC)
                               ▼
                            Gen 2 (Long-lived singletons, static caches)

3Code Example

C# 13 & .NET 9
using System;

public class GcGenerationsDemo
{
    public static void Main()
    {
        object obj = new object();
        Console.WriteLine($"Initial Generation: Gen {GC.GetGeneration(obj)}");

        GC.Collect(0); // Collect Gen 0 -> Promotes obj to Gen 1
        Console.WriteLine($"After Gen 0 Collection: Gen {GC.GetGeneration(obj)}");

        GC.Collect(1); // Collect Gen 1 -> Promotes obj to Gen 2
        Console.WriteLine($"After Gen 1 Collection: Gen {GC.GetGeneration(obj)}");
    }
}

4Expected Output

Initial Generation: Gen 0
After Gen 0 Collection: Gen 1
After Gen 1 Collection: Gen 2

5Key Takeaways

  • Gen 0 and Gen 1 collections are ephemeral, taking microseconds.
  • Gen 2 collections (Full GC) scan the entire heap and can cause latency spikes.
  • Aim to keep temporary objects in Gen 0 so they die immediately without promotion.