3.4 — Garbage Collection¶
← Roadmap · Section: 3. .NET Runtime and Platform Prev: 3.3 Managed vs unmanaged · Next: 3.5 Memory leaks
Markers: 🔥 🎯 · Confidence: 🔴 · Last reviewed: —
TL;DR¶
Garbage collection is .NET automatically finding objects that nothing is using any more and freeing the memory they occupied. You never write "delete this object" in C#.
- It works out what is still in use by starting from known roots and following every reference. Anything it cannot reach is garbage.
- It sorts objects into three generations by age, and mostly only cleans the youngest — because most objects die young.
- It manages memory only. Files, sockets and database connections still need
IDisposable.
Definitions¶
| Term | What it is in .NET | What it means |
|---|---|---|
| Heap | a region of memory | Where all reference-type objects live. Managed by the GC. |
| Stack | a region of memory | Where local variables live. Cleared automatically when a method returns — the GC is not involved. |
| Garbage collector (GC) | part of the CLR | The component that finds and frees unreachable objects. |
| Root | a starting point for the search | Somewhere the GC knows is definitely live: local variables of running methods, static fields, CPU registers. |
| Reachable | a property of an object | The GC can get to it by following references from a root. Reachable = keep. |
| Garbage | a property of an object | Not reachable from any root. Nothing can ever use it again, so its memory is freed. |
| Mark / Sweep / Compact | the three phases of a collection | Mark what is reachable → free what is not → slide survivors together to close the gaps. |
| Generation | an age bucket on the heap | Gen 0 (new), Gen 1 (survived once), Gen 2 (survived twice or more). |
| Promotion | what happens to a survivor | An object that survives a collection moves up to the next generation. |
| Collection | one run of the GC | A "Gen 0 collection" checks only Gen 0. A "Gen 2 collection" checks everything and is the expensive one. |
| LOH | a separate heap | Large Object Heap. Anything 85,000 bytes or larger goes here. Not compacted by default. |
| Fragmentation | a memory problem | Free space exists but is split into scattered gaps, so a large request still fails. |
GC.Collect() |
a static method | Forces a collection immediately. Almost always the wrong thing to call. |
| Finalizer | a method, written ~ClassName() |
Runs before an object's memory is reclaimed. Makes the object survive an extra collection, so avoid it. |
| Server GC / Workstation GC | two configuration modes | Server GC uses one heap per CPU core for speed. Workstation GC uses one heap, for lower memory. |
The concept¶
Start here: what problem does this solve?¶
In older languages like C, you asked for memory and had to give it back yourself:
Two things go wrong constantly. Forget to free and the memory is lost forever — a leak. Free it twice, or use it after freeing, and the program corrupts itself or crashes. Whole categories of security vulnerability come from exactly this.
.NET removes the problem by tracking it for you. You create objects and stop using them. The garbage collector notices and reclaims the memory.
The key question: how does it know what is garbage?¶
This is the part worth understanding properly, because everything else follows from it.
The GC does not count how many things point at an object. It does something simpler and more reliable.
It starts from places it knows are definitely live — the roots:
- Local variables in methods currently running
- Static fields
- CPU registers
Then it follows every reference from those roots, and from whatever they point to, and so on. Everything it can reach is in use. Everything it cannot reach is garbage.
A picture: a room full of objects, with strings tying some of them to hooks on the wall. The hooks are the roots. Anything you can trace back to a hook by following strings is kept. Anything with no path back to a hook — even if it is tied to other objects — is rubbish and gets swept away.
That last part matters. Two objects pointing at each other with no path from a root are both garbage. This is why .NET has no problem with circular references, whereas reference-counting systems do.
flowchart LR
R1["ROOT<br/>local variable"] --> A["Order"]
A --> B["Customer"]
A --> C["List of lines"]
R2["ROOT<br/>static field"] --> D["Cache"]
E["Old Order"] <--> F["Old Customer"]
style E fill:#f99,stroke:#900
style F fill:#f99,stroke:#900
The two red objects point at each other, but nothing reaches them from a root. Both are collected.
How it works¶
The simple version — the three phases¶
When a collection runs, the GC does three things:
- Mark. Start at the roots, follow every reference, mark everything reachable.
- Sweep. Everything unmarked is garbage. Its memory is now free.
- Compact. Slide the survivors together so free space is one continuous block rather than scattered gaps.
That third phase has a consequence worth knowing: objects move, so an object's address is
not stable. That is fine in normal C#, and it is exactly why you need fixed and pinning when
handing a pointer to native code — see 3.3.
Compaction also makes allocation extremely fast. Because free memory is one continuous block, allocating is just moving a pointer forward. It is close to free.
How it actually works — generations¶
Everything is built on one observation:
Most objects die very young. A string built inside a method, a DTO created for one request, the result of a LINQ query — the vast majority become garbage almost immediately. A small minority live for the whole application.
Scanning every object every time would be wasteful, since most old ones are still alive. So the GC splits the heap into three generations by age:
| Generation | Holds | Collected |
|---|---|---|
| Gen 0 | Brand new objects | Very often, very fast |
| Gen 1 | Objects that survived one collection | Less often |
| Gen 2 | Objects that survived twice or more | Rarely, and it is expensive |
The rules are simple:
- Every new object starts in Gen 0.
- Survive a collection and you are promoted to the next generation.
- A Gen 0 collection looks only at Gen 0. Often under a millisecond.
- A Gen 2 collection examines everything, including Gen 0 and Gen 1. This is a full collection and it is the expensive one.
flowchart LR
N["new object"] --> G0["Gen 0<br/>collected often<br/>very fast"]
G0 -->|"survived"| G1["Gen 1<br/>collected sometimes"]
G1 -->|"survived again"| G2["Gen 2<br/>collected rarely<br/>expensive"]
G0 -.->|"most objects<br/>die here"| X["freed"]
So the design makes the common case — short-lived objects — almost free, and accepts that the rare case is slow.
Why this matters for your code: an object that survives into Gen 2 is expensive to clean up later. Caching things "just in case" pushes objects into Gen 2 and makes your full collections slower and more frequent.
The Large Object Heap¶
Objects of 85,000 bytes or more go somewhere separate: the Large Object Heap, or LOH. Usually big arrays, large strings, or buffers.
The LOH has two special properties:
- It is collected only during a Gen 2 collection, so large objects hang around longer.
- It is not compacted by default, because moving an 800 KB object is expensive.
Not compacting causes fragmentation. Imagine allocating and freeing many differently-sized large arrays. You end up with free gaps scattered between live objects. Ask for a 500 KB array and, even with 2 MB free in total, there may be no single 500 KB gap — so the process asks the OS for more memory.
The result is an application whose memory keeps climbing even though nothing is really leaking. Repeatedly resizing large buffers is a classic cause.
The fix is not to force compaction — that exists but is very expensive:
// A last resort. Causes a long pause. Not for normal code.
GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
GC.Collect();
The real fix is to stop churning large objects. Reuse buffers with ArrayPool<T>, or avoid
allocating them at all with Span<T> — see
1.25 and
19.13.
The deeper detail — GC modes¶
Two settings matter in production, and interviewers do ask.
Workstation vs Server GC
| Workstation | Server | |
|---|---|---|
| Heaps | One | One per CPU core |
| GC threads | One | One per core, in parallel |
| Optimised for | Low latency, low memory | Maximum throughput |
| Default for | Desktop apps | ASP.NET Core |
Server GC gives each core its own heap and collection thread, so collections finish much faster on multi-core hardware. The cost is higher memory use, since there are several heaps.
⚠️ This is a real container gotcha. Server GC assumes it owns the machine. In a container limited to one core with a tight memory cap, several heaps waste memory and can push you past the limit — which the orchestrator handles by killing the container. If you run small containers, test with Workstation GC:
Modern .NET reads container limits much better than it used to, and .NET 9 enabled DATAS by default, which adapts the number of heaps to actual load. Still worth checking if containers are being killed for memory.
Concurrent / background GC lets most of a Gen 2 collection run on a background thread while your app keeps working, so the pause is much shorter. On by default; rarely changed.
Code¶
Do not call GC.Collect()¶
The GC has far better information than you do about when collecting is worthwhile. Forcing it usually:
- triggers a full Gen 2 collection, the most expensive kind
- promotes objects that would otherwise have died cheaply in Gen 0
- pauses all your threads for no benefit
The only defensible uses are in a benchmark harness, or immediately after deliberately dropping something very large. If you are reaching for it to fix a memory problem, the problem is a reference being held somewhere — see 3.5.
What you should actually do¶
The GC handles memory. It does not handle file handles, sockets or database connections:
// The GC will eventually free this object's memory,
// but the file stays LOCKED until Dispose runs.
await using var stream = File.OpenRead(path);
That distinction is the practical takeaway — see 1.21.
Reducing GC pressure, in order of usefulness:
// 1. Do not allocate in a loop when you can build once
var sb = new StringBuilder(); // not string concatenation
// 2. Reuse large buffers instead of allocating new ones
var buffer = ArrayPool<byte>.Shared.Rent(4096);
try { /* use it */ }
finally { ArrayPool<byte>.Shared.Return(buffer); }
// 3. Avoid the allocation entirely when slicing
ReadOnlySpan<char> slice = text.AsSpan(0, 100); // no new string
Interview questions¶
Q: How does the garbage collector know an object can be freed?
It uses reachability, not reference counting. It starts from a set of roots — local variables in running methods, static fields and CPU registers — and follows every reference from there, marking everything it can reach. Anything unmarked is unreachable and therefore garbage. An important consequence is that circular references are not a problem: two objects pointing at each other with no path from a root are both collected, whereas a reference-counting system would leak them.
Q: What are generations and why do they exist?
The heap is divided into three generations by age. New objects go into Gen 0, and anything surviving a collection is promoted upward. The design rests on the observation that most objects die very young — temporary strings, DTOs, LINQ results. So collecting only Gen 0 catches the vast majority of garbage while examining a small fraction of the heap, which makes it very fast. Gen 2 collections examine everything and are expensive, so the GC does them rarely. The practical implication is that keeping objects alive longer than necessary pushes them into Gen 2 and makes your expensive collections more frequent.
Q: What is the Large Object Heap and why does it cause problems?
Objects of 85,000 bytes or more — usually large arrays or strings — go on a separate heap. It
is collected only as part of a Gen 2 collection, so large objects survive longer, and it is not
compacted by default because moving very large objects is costly. Not compacting means
fragmentation: after allocating and releasing many differently-sized large objects you can have
plenty of free memory in total but no single contiguous block big enough for the next request,
so the process grows. The symptom is memory climbing steadily without an actual leak. The fix
is to stop churning large objects — pool buffers with ArrayPool<T> rather than allocating
fresh ones.
Q: What is the difference between Workstation and Server GC?
Workstation GC uses a single heap and a single collection thread, favouring low latency and low memory. Server GC creates one heap and one collection thread per CPU core, so collections run in parallel and finish much faster on multi-core hardware, at the cost of higher memory use. Server GC is the default for ASP.NET Core because throughput matters more there. The thing to watch is containers — Server GC assumes it owns the machine, so in a small container with a tight memory limit the multiple heaps can push you over and get the container killed. Modern .NET reads container limits much better, and .NET 9 turned on DATAS which adapts heap count dynamically, but it is still worth testing.
Q: Should you ever call GC.Collect()?
Almost never. The runtime has far better information about when collecting is worthwhile, and forcing it triggers a full Gen 2 collection — the most expensive kind — while also promoting objects that would otherwise have been collected cheaply in Gen 0. The only reasonable uses are benchmarking, where you want a known starting state, and immediately after deliberately dropping something very large. If someone is calling it to fix a memory problem, the real issue is something holding a reference, and forcing collections cannot help because the object is still reachable.
Traps ⚠️¶
- "The GC handles all cleanup." It handles memory only. Files, sockets and connections
need
IDisposable. - Calling
GC.Collect()to fix memory usage. If an object is still referenced, no amount of collecting frees it. - Forcing collection promotes objects, making things worse rather than better.
- Objects move during compaction. An object's address is not stable, which is why pinning exists for interop.
- The LOH threshold is 85,000 bytes — smaller than people expect. An array of about 21,000
ints already qualifies. - Server GC in a small container can get you OOM-killed. More heaps means more memory.
- A finalizer makes an object survive an extra collection. Never add one unless you truly need it — see 1.21.
- "No memory leaks in .NET" is false. You cannot leak by forgetting to free, but you can very easily leak by holding a reference. See 3.5.
Related¶
- 3.5 Memory leaks — how to leak in a managed language
- 3.3 Managed vs unmanaged — pinning and why objects move
- 1.21 IDisposable — what the GC does not do
- 1.1 Stack vs heap — what lives where
- 1.25 Span and Memory — avoiding allocation
- 19.13 Reducing allocations — pooling in practice
- 18.9 Production debugging — diagnosing GC problems