Volume 1 · Chapter 3 — Modern C# and .NET Foundations

Garbage Collection Internals

Goutham Mayaluri 9 min read .NETC#Garbage Collection

3.1 Introduction

The garbage collector is the CLR subsystem that automatically finds objects your code can no longer reach and reclaims their memory. It removes the hardest, most error-prone part of unmanaged programming - manual lifetime tracking - but it is not free: how much garbage you create, and how long objects live, directly drive GC frequency, pause times, and therefore application latency, throughput, and infrastructure cost. Understanding GC behavior is what lets you turn “the service pauses randomly” into a measurable, fixable problem.

3.2 Generational Collection

The .NET GC is generational, built on the empirical fact that most objects die young. New objects are allocated in Gen 0; survivors of a collection are promoted to Gen 1, and survivors of Gen 1 move to Gen 2 (long-lived objects). Gen 0 collections are extremely cheap and frequent; Gen 2 collections are expensive and rare. Low-allocation code keeps objects short-lived so they die in Gen 0 and never get promoted.

flowchart LR
  Alloc["new object"] --> G0["Gen 0 (nursery)"]
  G0 -- "survives GC" --> G1["Gen 1"]
  G1 -- "survives GC" --> G2["Gen 2 (long-lived)"]
  G0 -- "collected (cheap, frequent)" --> Free0["reclaimed"]
  G2 -- "collected (costly, rare)" --> Free2["reclaimed"]
  Big["large object (>= 85 KB)"] --> LOH["Large Object Heap"]
Generation Description
Gen 0 Newly allocated, short-lived objects - collected often and cheaply
Gen 1 Survived one Gen 0 collection - a buffer between short- and long-lived
Gen 2 Long-lived objects - collected rarely and expensively (full collection)

3.3 The Collection Process

When Gen 0 fills to a threshold, the GC pauses (briefly) to mark reachable objects from the roots (statics, locals, registers), reclaims the unreachable ones, promotes survivors, and compacts the heap so free space is contiguous. Because Gen 0 is small, this is fast. A Gen 2 collection scans the whole heap and is far more expensive - which is why the goal is to keep objects dying young.

3.4 The Large Object Heap

Objects of about 85,000 bytes or more (large arrays and buffers) are allocated on the Large Object Heap. The LOH is collected only during Gen 2 collections and, by default, is not compacted, so it fragments - free blocks that no single allocation can reuse - causing committed memory to climb and eventually risk out-of-memory. Repeatedly allocating and freeing large buffers is a classic cause.

3.5 Workstation vs Server GC

Workstation GC Server GC
One heap, one GC thread One heap and GC thread per logical core
Lower memory, responsive for UI Higher throughput via parallel collection
Default for desktop apps Default for ASP.NET Core services

Server GC is almost always correct for services, and concurrent GC (also default) performs most Gen 2 work on background threads to minimize pauses.

3.6 Finalizers and Weak References

A finalizer runs when an object is collected, giving a last chance to release unmanaged resources - but it delays cleanup (finalizable objects survive an extra GC cycle) and is non-deterministic, so deterministic cleanup viaIDisposableis strongly preferred. Weak references let you hold a reference to an object that the GC is still free to collect, useful for memory-sensitive caches.


// Prefer IDisposable over a finalizer; use a finalizer only as a safety net for unmanaged handles.
public sealed class NativeBuffer : IDisposable
{
    private IntPtr _handle = Native.Alloc();
    public void Dispose() { Native.Free(_handle); GC.SuppressFinalize(this); }
    ~NativeBuffer() => Native.Free(_handle);   // backstop if Dispose was missed
}

3.7 Diagnosing GC Problems

sequenceDiagram
  autonumber
  participant Eng as Engineer
  participant Ctr as dotnet-counters
  participant Dump as dotnet-gcdump
  participant Heap as Heap Analysis
  Eng->>Ctr: watch Gen2 count, heap size, % time in GC
  Ctr-->>Eng: Gen2 rising, heap not plateauing
  Eng->>Dump: capture gcdump on a live instance
  Dump-->>Heap: object graph + retention paths
  Heap-->>Eng: large object graphs from repeated serialization
  Eng->>Eng: reduce allocations, pool buffers, re-measure
Senior Interview Question

Why does generational garbage collection improve performance?

It exploits the empirical observation that most objects die young. By segregating new objects into a small Gen 0 and collecting that region frequently and cheaply, the GC does minimal work in the common case - short-lived allocations are reclaimed almost for free. Only objects that survive get promoted to older generations, which are collected far less often because they change less, so the expensive full-heap (Gen 2) collection happens rarely. This keeps the overall cost of memory management low compared with a scheme that scanned the entire heap on every collection. The practical implication for engineers is to keep objects short-lived so they die in Gen 0 and never get promoted, which is what low-allocation, GC-friendly code aims for.

Senior Interview Question

Why is the Large Object Heap performance-sensitive?

The LOH holds objects of about 85 KB or more, and it behaves differently from the normal generational heap in two costly ways. First, it is only collected during Gen 2 collections, which are the expensive, full-heap ones, so churning large objects drives up the frequency of the most expensive collections. Second, by default the LOH is not compacted, so freeing large blocks leaves gaps that later allocations cannot reuse - fragmentation - which makes the process’s committed memory climb even though logical usage is flat, eventually risking out-of-memory. Allocating large objects is also intrinsically more expensive. The mitigations are to avoid churning large temporary arrays and buffers, pool them withArrayPool, process data in smaller chunks, and, only if truly necessary, request LOH compaction as a rare maintenance action. In short, frequent large allocations amplify GC cost and cause fragmentation, so they should be minimized and pooled.

Senior Interview Question

What is the difference between Workstation and Server GC, and which should a web service use?

Workstation GC uses a single heap and GC thread and is tuned for lower memory use and responsiveness - the default for desktop/client apps. Server GC uses a separate heap and GC thread per logical core, collecting in parallel for much higher throughput at the cost of more memory - the default and correct choice for server workloads like ASP.NET Core, because a service handling many concurrent requests benefits enormously from parallel collection and can afford the extra memory. Both usually run concurrently (background Gen 2 collection) to minimize pause times. So a web service should use Server GC (which is the default for ASP.NET Core), while a memory-constrained container or a client app might prefer Workstation. The setting is configurable, and on tightly-packed containers you sometimes tune it, but the default of Server GC for services is right in the vast majority of cases.

Senior Interview Question

Why should finalizers generally be avoided in favor of IDisposable?

Because finalizers make cleanup non-deterministic and actually slower and later. An object with a finalizer cannot be reclaimed in the first collection that finds it unreachable; instead it is placed on a finalization queue, its finalizer runs on a dedicated thread at some unspecified later time, and only then can its memory be collected - so finalizable objects survive an extra GC cycle, delaying both their cleanup and their memory reclamation, and adding GC overhead. You also have no control over when (or promptly whether) the finalizer runs.IDisposablewithusingprovides deterministic cleanup - the unmanaged resource is released exactly when you are done, not at the GC’s convenience - which is what you want for scarce resources like connections and handles. The recommended pattern is to implementIDisposablefor deterministic release and, if the type wraps a raw unmanaged handle, add a finalizer only as a safety-net backstop (callingGC.SuppressFinalizeinDisposeso the backstop is skipped when cleanup was done properly). So finalizers are a last-resort safety net, not the primary cleanup mechanism.

Principal Engineer Question

An API's latency climbs during peak traffic and monitoring shows frequent Gen 2 collections. How do you investigate and fix it?

Frequent Gen 2 collections under load point to a high allocation rate and objects being promoted, so I attack the allocation sources with evidence. First I confirm withdotnet-counters- a high allocation rate, rising Gen 2 count, and elevated ”% time in GC” - which tells me GC pressure is the cause rather than, say, a downstream dependency. Then I capture an allocation trace (dotnet-tracewith allocation events) or a gcdump to find what is being allocated and retained; a common culprit, as in this scenario, is repeatedly serializing large object graphs, which produces large short-lived allocations that pressure the heap and the LOH. The fix is to reduce allocations on the hot path: reuse and pool buffers (ArrayPool), useSpan/stackallocto avoid temporary allocations, adopt a low-allocation serializer or source-generated serialization, avoid boxing and unnecessary LINQ in inner loops, and cache computed results. I confirm Server + concurrent GC is enabled. Crucially, the durable fix is producing less garbage, not asking the collector to run differently - so I profile allocations, make low-allocation a reviewed property of the hot path, and re-measure to prove the Gen 2 frequency and latency dropped. I’d also add a benchmark or allocation guard in CI to prevent regression.

3.8 Production Scenario

A .NET API’s latency climbs during peak traffic, and monitoring shows frequent Gen 2 collections. Allocation tracing reveals that each request serializes a large object graph, producing heavy short-lived allocations that pressure the heap. The team reduces allocations by switching to source-generated JSON, pooling buffers withArrayPool, and trimming the serialized payload - the Gen 2 frequency falls and latency returns to target. A CI benchmark now guards the hot path.

Chapter Revision Notes

  • Generational GC is cheap for short-lived objects - keep objects dying in Gen 0.
  • Gen 2 collections are full-heap and expensive; promotion is what to avoid.
  • The LOH (>= 85 KB) is collected rarely and fragments - pool large buffers.
  • Use Server + concurrent GC for services; prefer IDisposable over finalizers.
  • Diagnose GC problems with counters, allocation traces, and gcdumps - then reduce allocations.