In .NET, what triggers a gen 2 collection, and why does a service that churns 200 KB arrays see so many of them?
answer
- budgets, memory pressure, explicit calls
- 85,000-byte threshold
- the LOH has its own budget
- logically part of gen 2
- System.GC.LOHThreshold
basics
~20 sA .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.
solid answer
~50 sGen 2 (full) collections start from three kinds of event: an allocation budget running out, low memory, or an explicit `GC.Collect()`. The budget case has two sources. Gen 2's budget is consumed by objects promoted out of gen 1, so a steady trickle of medium-lived objects eventually forces a full collection. The **large object heap** has its own budget, consumed directly by allocations of 85,000 bytes or more, and because the LOH is collected only with gen 2, exceeding that budget triggers a gen 2 collection. A service that allocates and drops 200 KB buffers spends its LOH budget fast and gets a full collection every few megabytes of churn (about every 3 MB in one workstation-GC test run), each one also examining the whole small object heap. Low memory means an OS or host notification or, by default, a memory load of 90% or more, at which the GC turns more aggressive about full compacting collections.
code
csharp · 16 linesusing System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
Churn(50_000); // below the 85,000-byte threshold: small object heap
Churn(200_000); // above it: large object heap
static void Churn(int size)
{
int g0 = GC.CollectionCount(0), g1 = GC.CollectionCount(1), g2 = GC.CollectionCount(2);
long count = 4L * 1024 * 1024 * 1024 / size; // 4 GiB of short-lived arrays
byte[]? last = null;
for (long i = 0; i < count; i++) last = new byte[size];
Console.WriteLine($"{size,7:N0}-byte arrays: gen0 +{GC.CollectionCount(0) - g0}, " +
$"gen1 +{GC.CollectionCount(1) - g1}, gen2 +{GC.CollectionCount(2) - g2}");
GC.KeepAlive(last);
}go deeper
Recall that objects of 85,000 bytes or more go to the large object heap and that the LOH is collected only together with gen 2.
Explain the triggers: allocation budgets for gen 2 and the LOH, low memory and GC.Collect, and why churning large arrays turns into a stream of full collections.
Show how you would prove LOH churn with collection counts and GC memory info, then fix it by removing large temporaries rather than by tuning thresholds first.
Decide when a threshold or compaction setting is acceptable as a fleet default versus a code change, and require measured evidence before either ships.
## What a gen 2 collection is The .NET garbage collector divides the small object heap into generations 0, 1 and 2. Collecting a generation also collects every younger one, so a **gen 2 collection** examines the entire managed heap, including the **large object heap** (LOH) and the pinned object heap. That is why it is called a *full* collection, and why its cost grows with the size of the live heap rather than with the amount of garbage. ## The triggers The .NET docs list three conditions for any collection, and each can end in a gen 2: 1. **An allocation budget is exceeded.** Every generation has a threshold the GC tunes as the process runs. User code consumes gen 0's budget (small objects) and the LOH's budget (large objects); the GC itself consumes gen 1's and gen 2's budgets when it promotes survivors. Exceeding gen 2's budget, or the LOH's, triggers a gen 2 collection. A gen 0 collection that cannot free enough can also escalate to gen 1 and gen 2. 2. **Low memory.** The OS or the host reports low memory, or the memory load reaches the high-memory threshold, 90% by default (`System.GC.HighMemoryPercent`). Above it the GC favours full *compacting* collections to avoid paging; below it, it favours background collections, which pause less but shrink the heap less. In a container, the memory limit counts as the physical memory. 3. **`GC.Collect()` is called.** The parameterless overload forces a full blocking collection of all generations, LOH included. ## Why large arrays drive gen 2 collections An allocation of **85,000 bytes or more** goes to the LOH. The size counts the whole object, so on 64-bit a `byte[]` of 84,976 elements (plus the array's header and length) already qualifies. The LOH is a physical heap that is logically collected as part of gen 2, so: - every large allocation consumes the LOH budget directly, with no cheap gen 0 collection to absorb short-lived arrays; - when the budget runs out, the GC runs a gen 2 collection, even if gen 2 itself barely changed; - that collection also examines the whole small object heap, so a big long-lived heap (a cache, an order book) makes every LOH-triggered collection expensive. Large allocations are also costly in themselves: the runtime clears the memory of every new object, and for a large array that clearing dominates the allocation cost. | Allocation | Heap | First collection that can reclaim it | |---|---|---| | `new byte[50_000]` | Gen 0 (small object heap) | Gen 0 | | `new byte[200_000]` | Large object heap | Gen 2 | ## LOH fragmentation and compaction By default the GC **sweeps** the LOH instead of compacting it: dead large objects become free-list entries that later large allocations reuse, and copying large objects around is avoided. Mixed sizes therefore leave gaps, so the LOH can hold plenty of free space and still need fresh memory for a slightly larger array. You can request compaction once: ```csharp GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce; ``` The next blocking gen 2 collection compacts the LOH, and the property goes back to `Default`. The .NET docs also state that the LOH is compacted automatically when a heap hard limit is in force (a container memory limit, `GCHeapHardLimit` or `GCHeapHardLimitPercent`), and that a non-zero `System.GC.ConserveMemory` compacts it when it is too fragmented. ## Fixing LOH-driven gen 2 collections - **Stop allocating large temporaries.** Reusing large buffers instead of allocating fresh ones is the docs' own recommendation; the mechanics of pooling belong with the material on memory buffers. - **Keep buffers below the threshold** when the data can be processed in chunks smaller than 85,000 bytes. - **Raise the threshold** only with evidence: `System.GC.LOHThreshold` in runtimeconfig.json (or `DOTNET_GCLOHThreshold` as hex) must be larger than 85,000. Objects under the new threshold then die cheaply in gen 0, but survivors are copied during compaction and promoted like any small object. - **Remove `GC.Collect()` calls** from service code; each one is a full blocking collection. - **Measure** with `GC.CollectionCount(2)` and `GC.GetGCMemoryInfo()` before and after; counts and rates depend on the machine and the GC mode.
- Why does the .NET large object heap fragment, and what can you do about it?By default the GC sweeps the LOH instead of compacting it, turning dead large objects into free-list entries, so mixed sizes leave gaps that a slightly larger array cannot use. Setting `GCSettings.LargeObjectHeapCompactionMode` to `CompactOnce` compacts it during the next blocking gen 2 collection, after which the setting returns to `Default`. A heap hard limit, such as a container memory limit, also makes the runtime compact the LOH.
- When would you raise System.GC.LOHThreshold, and what does it cost?When objects just above 85,000 bytes are churned and a measured gen 2 rate shows LOH-triggered collections. Raising the threshold (the value must exceed 85,000) lets those short-lived objects die in cheap gen 0 collections. The cost is that the ones that survive are copied when the small object heap compacts and promoted like any other object. It goes in runtimeconfig.json, or as hex in `DOTNET_GCLOHThreshold`.
- Does background GC make LOH-triggered gen 2 collections harmless?No. Background GC, on by default, lets a gen 2 collection mark on dedicated threads while the app runs, but it still has short pauses, ephemeral collections during it are blocking, and the GC can still choose a blocking full collection, for example under high memory load. The work also scales with the live heap, so frequent LOH-triggered gen 2 collections still cost CPU and latency.
- A gen 2 collection only happens when the process is about to run out of memory.
- Large objects start in gen 0 and move to the large object heap when promoted.
- The large object heap is compacted on every gen 2 collection, so it never fragments.
- Raising GCLOHThreshold to several megabytes is a free fix for large-object churn.
- Background GC means gen 2 collections never pause the application.