Volume 7 · Chapter 2 — Advanced .NET Engineering, Performance & Production Excellence
Garbage Collection and Memory Management
2.1 Introduction
The garbage collector is the single most impactful runtime subsystem for enterprise performance. It frees engineers from manual memory management, but it does not free them fromthinkingabout memory: allocation patterns drive GC frequency, GC frequency drives pause times, and pause times drive tail latency. Understanding how the GC works turns “the service pauses randomly” into a solvable, measurable problem.
2.2 Stack, Heap, and Value vs Reference Types
Value types (structs, primitives) live where they are declared - on the stack for locals, or inline within their containing object on the heap. Reference types (classes) always live on the managed heap, with a reference to them stored wherever they are used. The stack is reclaimed automatically as methods return; the heap is the GC’s responsibility.
struct Point { public int X, Y; } // value type - copied by value
class Node { public int Value; } // reference type - lives on the heap
void Demo()
{
Point p = new() { X = 1, Y = 2 }; // on the stack (a local)
Node n = new() { Value = 3 }; // object on the heap; n is a stack reference
// Boxing: putting a value type on the heap - a common hidden allocation.
object boxed = p; // allocates! p is copied to the heap
}
2.3 Generational Garbage Collection
The .NET GC is generational, built on the empirical observation that most objects die young. New objects are allocated in Gen 0; those that survive 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. The goal of memory-conscious code is to keep 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"]
2.4 The Large Object Heap
Objects of 85,000 bytes or more (typically 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 can fragment - you may have free space that no single allocation can use. Repeatedly allocating and freeing large buffers is a classic cause of climbing memory and eventual out-of-memory failures.
2.5 Workstation vs Server GC
| Workstation GC | Server GC | |
|---|---|---|
| Heaps | One | One per logical core |
| Throughput | Lower | Higher (parallel collection) |
| Memory use | Lower | Higher |
| Best for | Desktop / low-core | Server apps, high throughput |
Server GC is the default for ASP.NET Core and is almost always correct for services. Concurrent GC (also default) performs most Gen 2 work on background threads to minimize pauses.
2.6 Deterministic Cleanup: IDisposable and using
The GC reclaims memory but does not deterministically release unmanaged resources like file handles, sockets, and database connections. Those implementIDisposableand must be disposed promptly, ideally withusing. Relying on finalizers for this is a bug: finalization is non-deterministic and actually keeps objects alive longer.
// 'using' guarantees Dispose runs even on exception - deterministic cleanup.
public async Task<decimal> GetBalanceAsync(Guid id, CancellationToken ct)
{
await using var conn = new SqlConnection(_connectionString);
await conn.OpenAsync(ct);
await using var cmd = new SqlCommand("SELECT Balance FROM Accounts WHERE Id=@id", conn);
cmd.Parameters.AddWithValue("@id", id);
return (decimal)(await cmd.ExecuteScalarAsync(ct))!;
}
2.7 Common Memory Leak Patterns
Managed leaks are really “unintended retention”: the object is still reachable, so the GC cannot collect it. The usual culprits are static collections that grow forever, event handlers that keep subscribers alive, captured variables in long-lived closures, and caches without eviction.
// Leak: the publisher's event holds a reference to every subscriber forever.
public sealed class PriceTicker
{
public event EventHandler<decimal>? PriceChanged;
}
public sealed class Widget : IDisposable
{
private readonly PriceTicker _ticker;
public Widget(PriceTicker t) { _ticker = t; _ticker.PriceChanged += OnPrice; }
void OnPrice(object? s, decimal p) { /* ... */ }
// Without unsubscribing, every Widget ever created stays alive via the event.
public void Dispose() => _ticker.PriceChanged -= OnPrice;
}
2.8 Reducing Allocations with Span and Pooling
Span<T>andMemory<T>let you work with slices of arrays, stack memory, and strings without copying or allocating.ArrayPool<T>and object pooling reuse expensive buffers instead of allocating and discarding them, which directly reduces GC pressure on hot paths.
// Parse without allocating substrings, and reuse a pooled buffer.
static int SumCsv(ReadOnlySpan<char> line)
{
int sum = 0;
foreach (var range in line.Split(',')) // no intermediate string[]
sum += int.Parse(line[range]);
return sum;
}
byte[] buffer = ArrayPool<byte>.Shared.Rent(8192);
try { /* use buffer */ }
finally { ArrayPool<byte>.Shared.Return(buffer); }
2.9 Diagnosing a Memory Problem in Production
sequenceDiagram autonumber participant Eng as Engineer participant Ctr as dotnet-counters participant Dump as dotnet-dump / dotnet-gcdump participant Heap as Heap Analysis Eng->>Ctr: watch Gen2 count, heap size, % time in GC Ctr-->>Eng: heap growing, Gen2 rising, no plateau Eng->>Dump: capture gcdump on a live instance Dump-->>Heap: object graph + retention paths Heap-->>Eng: 2M EventHandler delegates retained by PriceTicker Eng->>Eng: fix: unsubscribe in Dispose; add cache eviction
How does generational garbage collection improve performance?
It exploits the fact that most objects die young. By segregating new objects into Gen 0 and collecting that small 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. This means the expensive full-heap (Gen 2) collection happens rarely, and the overall cost of memory management stays low relative to a scheme that scanned the whole heap every time.
What is the difference between a memory leak in .NET and one in C++?
In C++ a leak is memory you allocated and never freed - it becomes unreachable and lost. In .NET the GC reclaims everything unreachable, so a “leak” is the opposite problem: an object that isstill reachablewhen you no longer want it, so the GC correctly refuses to collect it. The fix is not to free memory but to remove the reference keeping it alive - unsubscribe from the event, clear the static list, evict from the cache. Diagnosis therefore focuses on retention paths (who holds a reference), which is exactly what a gcdump reveals.
What is boxing and why does it hurt performance?
Boxing is wrapping a value type in an object so it can be treated as a reference type - assigning anintto anobject, or using a value type through a non-generic interface or collection. Each box allocates on the heap and copies the value, and unboxing copies it back. On a hot path this generates constant Gen 0 garbage and adds indirection. It is avoided by using generics (which are specialized for value types without boxing), generic collections, and, in newer .NET, features that keep values on the stack. Hidden boxing (for example instring.Formator LINQ over non-generic sequences) is a common, easily overlooked source of allocations.
When and why would you call GC.Collect() manually?
Almost never. The GC is self-tuning and manual collections usually hurt: forcing a full collection promotes surviving objects and disrupts the runtime’s heuristics. Legitimate exceptions are narrow - for example, immediately after a deliberate, one-off release of a very large working set (a bulk import finishing) where you want to return memory to the OS, or in a benchmark to isolate a measurement. Even then, preferGCSettingstuning and better allocation patterns over forcing collections. If you feel the need to call it routinely, the real problem is the allocation pattern.
What is the Large Object Heap and what problems does it cause?
The LOH holds objects of 85 KB or more, typically big arrays and buffers. Because it is collected only during costly Gen 2 collections and is not compacted by default, it fragments: freed large blocks leave gaps that later allocations cannot reuse, so the process’s committed memory climbs even though logical usage is flat, eventually risking out-of-memory. Mitigations include pooling large buffers withArrayPool, avoiding churn of large temporary arrays, processing data in smaller chunks, and, if truly necessary, requesting LOH compaction viaGCSettings.LargeObjectHeapCompactionModeas a rare maintenance action.
How do you troubleshoot steadily climbing memory in a production .NET service?
I start with evidence, not code.dotnet-counterstells me whether the managed heap is growing without plateauing and whether Gen 2 and ”% time in GC” are rising - distinguishing a managed retention problem from unmanaged or fragmentation issues. If it looks managed, I capture adotnet-gcdump(or two, spaced apart) from a live instance and compare object counts to find what is growing, then follow the retention paths to the root holding those objects - commonly an event handler, a static or singleton-held collection, or an unbounded cache. The fix targets the reference, not the memory: unsubscribe, add eviction, or bound the collection. If the heap is flat but process memory grows, I look at LOH fragmentation or unmanaged handles instead. Finally I add a regression guard - a memory metric alert or a load test that watches for unbounded growth.
A latency-sensitive service has acceptable average latency but its p99 is dominated by GC pauses. What do you do?
Tail latency from GC almost always traces back to allocation rate and promotion. I’d measure the allocation rate and Gen 2 frequency, then attack the sources: pool large and frequently used buffers (ArrayPool, object pools), useSpan/stackallocto avoid temporary allocations on hot paths, remove boxing and unnecessary LINQ in inner loops, and cache computed results. On the runtime side I’d confirm Server + concurrent GC is enabled and, for extreme cases, consider tuning (for example higher-latency-tolerant settings or, in specialized scenarios,GCSettings.LatencyModeduring critical sections). The strategic point is that the durable fix is producing less garbage, not asking the collector to run differently - so I invest in allocation profiling (BenchmarkDotNet’s memory diagnoser, a trace with allocation events) and make low-allocation a reviewed property of the hot path.
2.10 Banking Enterprise Scenario
A bank’s statement-generation service leaks memory during month-end batches. Counters show the heap climbing with every batch and Gen 2 never settling. A gcdump reveals millions of retained delegates: a per-statement component subscribes to a long-lived market-data ticker but never unsubscribes, so every statement object is pinned alive through the event. The team implementsIDisposableto unsubscribe, switches the large PDF buffers toArrayPoolto stop LOH churn, and adds a heap-size alert. Batch memory now plateaus and the recurring out-of-memory restarts stop.
Chapter Revision Notes
- Value types live on the stack/inline; reference types live on the managed heap.
- Generational GC is cheap for short-lived objects - keep objects dying in Gen 0.
- The LOH (>= 85 KB) is rarely collected and fragments - pool large buffers.
- Use Server + concurrent GC for services; dispose unmanaged resources deterministically.
- Managed “leaks” are unintended retention - fix the reference, not the memory.
- Reduce GC pressure with Span, stackalloc, and pooling on hot paths.