skip to content

Managed Heap & GC Modes

Generations, the large and pinned object heaps, workstation vs server modes and finalization cost decide pause times. Interviewers ask what triggers a gen 2 collection.

on this pageshow

explore

questions

6

In .NET, what are garbage-collection generations 0, 1 and 2, and how does an object move from one to the next?

level: juniorimportance: must knowfreq 75%

answer

  1. most objects die young
  2. survivors move up one step
  3. collecting a generation includes younger ones
  4. GC.GetGeneration shows the current one

basics

~20 s

The .NET GC puts new small objects in gen 0; an object that survives a gen 0 collection is promoted to gen 1, and one that survives a gen 1 collection to gen 2, which only a full (gen 2) collection reclaims.

solid answer

~40 s

The managed heap is generational because most objects die young. `new` places a small object in **gen 0**; when gen 0's allocation budget runs out, the GC collects gen 0 and promotes every survivor to **gen 1**, a buffer for objects that were only in flight. A gen 1 collection also collects gen 0, and its gen 1 survivors move to **gen 2**, the home of long-lived data such as caches and singletons; survivors of a gen 2 collection stay in gen 2. Collecting a generation always collects the younger ones too, so a gen 2 collection is a *full* collection. Objects of 85,000 bytes or more skip the ladder: they go to the large object heap, which is collected only with gen 2, and `GC.GetGeneration(obj)` reports 2 for them.

code

csharp · 12 lines
csharp
var order = new object();
Console.WriteLine($"new object: gen {GC.GetGeneration(order)}");

GC.Collect(0); // survives a gen 0 collection
Console.WriteLine($"after gen 0 GC: gen {GC.GetGeneration(order)}");

GC.Collect(1); // survives a gen 1 collection
Console.WriteLine($"after gen 1 GC: gen {GC.GetGeneration(order)}");
GC.KeepAlive(order);

var snapshot = new byte[100_000]; // 85,000 bytes or more: large object heap
Console.WriteLine($"new 100,000-byte array: gen {GC.GetGeneration(snapshot)}");

go deeper

for a junior

Recall the three generations, that a survivor moves up one generation per collection, and that collecting a generation also collects every younger one.

for a middle

Explain the gen 0 allocation budget that triggers most collections, why gen 1 acts as a buffer, and why objects of 85,000 bytes or more skip the ladder.

for a senior

Connect promotion to production cost: objects that live just long enough to reach gen 2, such as short-lived cache entries, drive full collections and their pauses.

for a principal

Treat generations as the team's cost model: allocation rate sets gen 0 frequency, survival into gen 2 sets full-collection cost, and reviews can target both.

## Why the .NET heap is split into generations The .NET garbage collector (GC) reclaims memory that the program can no longer reach. Examining every object on every collection would be expensive, so the GC divides the **small object heap** into three **generations** and collects the young part far more often than the old part. The design rests on two observations the .NET docs state directly: compacting part of the heap is faster than compacting all of it, and newer objects tend to have shorter lifetimes than older ones. In a typical service, the strings, lists and DTOs built for one request are garbage by the time the request ends, while caches, configuration and singletons live for the whole process. ## The three generations - **Generation 0** holds newly allocated small objects. It is collected most often, and most objects die here without ever being promoted. - **Generation 1** holds objects that survived one gen 0 collection. It is a buffer between short-lived and long-lived data: objects that were merely *in flight* when a gen 0 collection happened (a half-processed request, a pending message) usually die in gen 1 instead of reaching gen 2. - **Generation 2** holds long-lived objects: survivors of a gen 1 collection, plus everything that survives a gen 2 collection, which stays in gen 2. Gen 0 and gen 1 together are called the **ephemeral generations**. The **large object heap** (LOH) and the **pinned object heap** (POH) sit beside them, and `GC.GetGeneration` reports 2 for their objects; LOH objects in particular are collected only when gen 2 is. ## Promotion, step by step 1. `new Order()` allocates in gen 0 by bumping a pointer, which is almost as cheap as a stack allocation. 2. Allocation consumes gen 0's **allocation budget**, a threshold the GC keeps tuning as the process runs. When it is used up, the next allocation triggers a gen 0 collection. 3. The GC marks what is reachable from the roots (static fields, locals on thread stacks, CPU registers, GC handles and the finalization queue), compacts the survivors and promotes them to gen 1. 4. A gen 1 collection collects gen 1 *and* gen 0; its gen 1 survivors move to gen 2. 5. A gen 2 collection collects everything, including the LOH, which is why it is called a **full GC**. You can watch promotion with `GC.GetGeneration`: ```csharp var order = new object(); GC.Collect(0); Console.WriteLine(GC.GetGeneration(order)); // 1 ``` ## What each collection costs | Collection | What it examines and reclaims | What drives its cost | |---|---|---| | Gen 0 | Gen 0 only | The volume of gen 0 survivors | | Gen 1 | Gen 0 and gen 1 | Survivors of both generations | | Gen 2 (full) | All generations, the LOH and the POH | The size of the live heap | The .NET docs put it in one line: how often and how long collections run is the result of the volume of allocations and the amount of memory that survives. A high **allocation rate** means more frequent gen 0 collections; objects that live *just long enough* to reach gen 2 (a cache entry kept for a few minutes, a buffer held across an await) make full collections more frequent and more expensive. When the GC sees a high survival rate in a generation, it raises that generation's budget so the next collection reclaims more per run. ## Where large, pinned and frozen objects fit - An object of **85,000 bytes or more** (usually an array) goes straight to the LOH. On 64-bit, `new byte[100_000]` reports generation 2 the moment it is allocated. - `GC.AllocateArray<T>(length, pinned: true)` allocates on the POH, where objects are never moved, so the array can be handed to native code without a pinning handle; it too reports generation 2. - Since .NET 8, `GC.GetGeneration` can return `int.MaxValue` for objects the runtime placed on a non-GC (frozen) heap, such as string literals; earlier releases returned 2. Code should never use the result as an array index. ## Common misreadings - Generations are about **surviving collections**, not about elapsed time: an object can stay in gen 0 for minutes if no collection runs. - Value-type locals such as an `int` are not separate gen 0 allocations; the managed heap holds objects, including arrays and boxed values. - A gen 2 collection does not skip gen 0 and gen 1; it collects all of them. - Calling `GC.Collect()` to "keep gen 2 small" forces full blocking collections and promotes live gen 0 objects earlier than the GC would have, which usually makes things worse.

  • What triggers a gen 0 collection in .NET?
    Mostly allocation: gen 0 has an allocation budget the GC tunes as the process runs, and when it is used up the next allocation triggers a gen 0 collection. Low physical memory reported by the OS or host and an explicit `GC.Collect` call also start collections. If a gen 0 collection does not free enough, the GC can go on to collect gen 1 and then gen 2.
  • Why does .NET use three generations instead of two?
    Gen 1 is a buffer. Objects alive only because a request was in progress when a gen 0 collection ran get promoted to gen 1 and usually die there at the next gen 1 collection. Without that buffer they would land in gen 2, where only a full collection reclaims them, so every in-flight object would push the process towards more full collections.
  • Can GC.GetGeneration return anything other than 0, 1 or 2?
    Yes. Since .NET 8 it can return `int.MaxValue` for objects on a non-GC (frozen) heap, such as string literals, where earlier releases returned 2. Objects on the large object heap report 2, the generation they are collected with, and so do objects on the pinned object heap.

Generations work like an office inbox, a pending tray and a filing cabinet: most papers are binned straight from the inbox, the few still needed go to the pending tray, and only papers that outlast the pending tray get filed, where clearing out means going through the whole cabinet.

  • Objects are promoted to an older generation after a fixed amount of time.
  • A gen 2 collection only examines gen 2 objects and leaves gen 0 and gen 1 alone.
  • Every new object starts in gen 0, including a one-megabyte array.
  • Every local variable, even an int, is allocated in gen 0.
  • Calling GC.Collect regularly keeps gen 2 small and the application fast.
open as a page

In .NET, what triggers a gen 2 collection, and why does a service that churns 200 KB arrays see so many of them?

level: middleimportance: must knowfreq 60%

basics

~20 s

A .NET gen 2 collection starts when gen 2's or the large object heap's allocation budget runs out, when memory is low, or when code calls GC.Collect. Arrays of 85,000 bytes or more go to the LOH, so churning them triggers full collections.

open as a page

In .NET 10, how do workstation GC, server GC and DATAS differ, and which does a console or ASP.NET Core app get by default?

level: middleimportance: must knowfreq 65%

basics

~20 s

Workstation GC uses one heap and collects on the allocating thread; server GC collects up to one heap per logical CPU on dedicated threads. Console apps default to workstation, ASP.NET Core apps to server, whose heap count DATAS has adapted since .NET 9.

open as a page

A .NET 10 order-matching service in a 2 GiB container has p99 latency spikes that line up with gen 2 collections; how do you find the cause and fix it?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Classify the gen 2 collections and find their trigger with GC.GetGCMemoryInfo and GC.CollectionCount: LOH churn, a heap near the container's default 75% limit, GC.Collect calls or gen 2 growth. Remove that trigger before tuning GC settings.

open as a page

Why does a .NET object with a finalizer survive at least one garbage collection longer than the same object without one, and what does that cost?

level: seniorimportance: should knowfreq 35%

basics

~20 s

When the .NET GC finds a finalizable object unreachable, it cannot free it: it queues the object for the finalizer thread, so the object and everything it references survive that collection and are promoted. Only a later collection reclaims them.

open as a page

As a lead, which GC settings would you standardise for a fleet of .NET 10 services in memory-limited containers, and how would you decide them?

level: principalimportance: should knowfreq 30%

basics

~20 s

Write one explicit baseline in a shared Directory.Build.props: GC flavor, DATAS, heap hard limit percent and any memory-conservation level, chosen per service class from load tests, with GC signals on every dashboard and evidence for each exception.

open as a page