Skip to content
Tutorials Center
My learning

Topics

Lesson 107 of 182 ยท Memory and Performance

Garbage Collection

Understand how the .NET garbage collector finds dead objects, why it uses generations, what roots and finalizers are, and how to work with it instead of fighting it.

In C# you create objects with new and never free them. Somewhere behind the scenes, a component of the runtime called the garbage collector (GC) notices which objects your program can no longer reach and reclaims their memory. This is why C# programs do not suffer from the classic C bugs of forgetting to free memory, freeing it twice or using it after it was freed.

The GC is not magic, though, and "I never think about memory" is not a good strategy for programs that must be fast or run for weeks. This lesson explains in plain words how the collector decides what is garbage, why it sorts objects into generations, what a root is, how finalizers and weak references fit in, and which habits help the GC instead of fighting it. It builds on value and reference types and on IDisposable, and it prepares you for Span and Memory and boxing.

Where objects live: the stack and the heap

Local variables of value types such as int or double live in the method's stack frame and vanish when the method returns. Objects of reference types (classes, arrays, strings, delegates) live on the managed heap, and the variable on the stack only holds a reference to them. The heap is what the GC manages.

Allocation on the managed heap is very cheap. The runtime keeps a pointer to the next free spot, and new mostly means "move the pointer forward by the object's size and clear the memory". The cost comes later, when the GC has to clean up. That is the key trade-off of .NET memory management: allocation is fast, collection costs time in proportion to how much live data it has to look at.

Roots and reachability

How does the GC know an object is garbage? Not by counting references. It asks a simpler question: can the program still reach this object?

The GC starts from a set of roots:

  • local variables and parameters on every thread's stack (and in registers),
  • static fields,
  • objects pinned by native code or handles,
  • the finalization queue (more on that below).

From the roots it follows every reference, marking each object it visits as alive. Whatever it never visits is garbage. Because it follows references from the roots, two objects that point at each other but are unreachable from any root are still collected. Circular references are not a leak in C#.

C# An unreachable object disappears

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The WeakReference observes an object without keeping it alive. Once the strong reference is gone (the method returned), a collection can reclaim the object, so the second line prints False. We create the object in a separate method on purpose: a local variable in the method that runs the collection can still look like a live root.

Calling GC.Collect() in this lesson is for demonstration only. In real programs you almost never call it: the GC knows far more about the heap than you do, and forcing a collection usually makes the program slower. We come back to this below.

A reference you still hold keeps the object alive

The opposite is just as important. If a long-lived object (a static field, a cache, an event publisher) holds a reference to something, that something cannot be collected, even if you think you are done with it. This is how .NET programs "leak" memory.

C# A static list keeps objects alive

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The array was only ever created inside Register, yet it survives because the static Registry.Items list is a root. Typical real-world versions of this bug are event handlers that are never unsubscribed (events), static caches without a size limit and singletons that collect data forever.

The phases of a collection: mark, sweep, compact

A collection works in phases. Mark walks from the roots and flags every reachable object. Sweep (the "plan" step) finds the gaps left by unreachable objects. Compact then slides the surviving objects together and fixes every reference to them, so free memory is one contiguous block and allocating a new object is just moving a pointer. Compaction costs time because objects are copied, which is why the large object heap is normally not compacted. Collection is also non-deterministic: you cannot know when it will run, only that it will before memory runs out.

Advantages: no manual free, no use-after-free bugs and fast allocation. Limitations: unpredictable (usually short) pauses, extra memory headroom, and no cleanup of non-memory resources, which is why disposal exists.

Generations: most objects die young

Marking everything on every collection would be slow for a big heap. The .NET GC relies on an observation that holds for nearly all programs, the generational hypothesis:

  • Most objects die young (a temporary string, a loop's helper object).
  • Objects that have survived a while tend to live much longer (caches, configuration, a web app's services).

So the heap is split into generations:

Generation Holds Collected
Gen 0 Newly allocated objects Very often, and very quickly
Gen 1 Survivors of one gen 0 collection, a buffer between young and old Less often
Gen 2 Long-lived survivors Rarely, and it is the expensive one

When gen 0 fills up, the GC collects only gen 0. Survivors are promoted to gen 1, and gen 1 survivors on to gen 2. A gen 2 collection examines the whole heap, so the runtime avoids it until needed. You can observe promotion with GC.GetGeneration.

C# Watching an object get promoted

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

GC.KeepAlive is there on purpose: without it, the JIT may decide the array is no longer needed after its last use and treat it as dead earlier than you expect. In optimized builds a local variable stops being a root after its last read, not at the end of its scope. That is correct and allows more memory to be reclaimed, but it surprises people who test with WeakReference.

The large object heap

Objects of about 85,000 bytes or more (typically big arrays) go to a separate area, the large object heap (LOH). Copying a huge array during compaction would be expensive, so the LOH is collected together with gen 2 and, by default, is not compacted. Two consequences:

  • Allocating many large temporary arrays makes gen 2 collections frequent. Reuse buffers instead (see ArrayPool in fast lookups).
  • Lists that grow by doubling can leave several dead large arrays behind. Give a List<T> a starting capacity when you know the size.
C# Large arrays start in the last generation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The large array reports generation 2 immediately, because the LOH is logically part of gen 2.

Measuring: allocated bytes and collection counts

You cannot manage what you cannot measure. Two methods help when you are learning:

  • GC.CollectionCount(n) returns how many times generation n has been collected.
  • GC.GetAllocatedBytesForCurrentThread() returns the total bytes this thread has allocated so far, a precise number that does not depend on when the GC runs.

Absolute collection counts vary between machines and runs, so compare differences and prefer allocated bytes when you need a stable metric. We use that idea heavily in measuring performance.

C# Counting allocations and collections

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Finalizers and the cost of surviving

A class can declare a finalizer (~ClassName()), a method the GC calls after it has found the object to be garbage. Finalizers exist as a last-resort safety net for unmanaged resources (see IDisposable for the right way to clean up). They have real costs:

  1. An object with a finalizer is registered in a special queue when it is allocated, which makes allocation slower.
  2. When it becomes unreachable, the GC cannot free it right away. It moves it to the freachable queue, and a dedicated finalizer thread runs the method later.
  3. The object (and everything it references) therefore survives at least one extra collection, so it gets promoted to an older generation and lives longer than needed.

You normally call GC.SuppressFinalize(this) inside Dispose() so that properly disposed objects skip all of that. You can also see that the finalizer runs on another thread and at a time you do not control.

C# A finalizer runs after the object is unreachable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

GC.WaitForPendingFinalizers() blocks until the finalizer thread has drained its queue, so the output order is predictable here. In real programs you do not get that guarantee, and finalizers may not run at all when the process exits. Never put logic there that must happen.

Weak references and caches

Sometimes you want to remember an object if it is still around but not be the reason it stays alive, for example a cache of expensive results. A WeakReference<T> holds an object without making it a root. After a collection the target may be gone, so you always have to ask with TryGetTarget.

C# A tiny cache with WeakReference of T

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Weak references are a niche tool. For ordinary caches, a bounded MemoryCache with expiration is easier to reason about (see fast lookups), and ConditionalWeakTable<TKey, TValue> is the right tool for attaching extra data to objects you do not own.

Workstation, server, concurrent: GC flavors

.NET ships two collector modes:

  • Workstation GC is the default for desktop and console apps. It aims at low latency and a small footprint, and it uses one heap.
  • Server GC uses one heap and one dedicated GC thread per logical core. Collections are faster for big heaps but use more memory. ASP.NET Core apps are often configured with it when throughput matters.

On top of that, background (concurrent) GC lets gen 2 collections run mostly while your threads keep working, so pauses are short. You choose the mode in the project file or runtimeconfig.json. This is a read-only example, because our editor does not have a project file:

XML
<!-- MyApp.csproj (shown for reference; not runnable in the editor) -->
<PropertyGroup>
  <ServerGarbageCollector>true</ServerGarbageCollector>
  <ConcurrentGarbageCollection>true</ConcurrentGarbageCollection>
  <TieredPGO>true</TieredPGO>
</PropertyGroup>

You can read the current settings at run time:

C# Which GC mode is this?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

On our server this prints False and Batch: workstation GC with background collection switched off. On your own machine a console app normally reports Interactive because concurrent GC is on.

Habits that help the GC

  • Allocate less, not "smarter". The cheapest object is the one never created. Avoid temporary strings in loops (use StringBuilder), avoid boxing, and prefer spans for slicing.
  • Do not call GC.Collect(). It forces an expensive full-heap pass and can promote objects that would have died young. The few legitimate uses are tests, benchmarks and a rare "load finished, now idle" moment in a long-running tool.
  • Dispose what you open. The GC only knows about memory; files, sockets and connections need using.
  • Watch long-lived references. Static collections, unsubscribed events and captured variables in long-lived lambdas are the usual suspects when memory keeps growing.
  • Reuse big buffers. Pool arrays that would land on the LOH.
  • Keep objects small and short-lived when you can; structs avoid heap allocation altogether, but only when they are small (see structs).

Garbage collection pauses your threads briefly for some phases. For most programs the pauses are far too short to notice. If you measure that GC time is a real problem, reduce allocations first, then tune the GC mode. Tuning flags are the last step, not the first.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How does the .NET garbage collector decide that an object is garbage?

    The GC traces references from roots and keeps what it can reach. It does not count references, so objects that only point at each other are still collected once no root reaches them.
  2. 2. Why does the GC use generations?

    The generational hypothesis says most objects are short-lived. Collecting gen 0 often and gen 2 rarely avoids examining the entire heap every time.
  3. 3. What is the main problem with giving a class a finalizer?

    Finalizable objects are queued for the finalizer thread instead of being freed straight away, which keeps them (and what they reference) alive longer. Timing is not guaranteed.
  4. 4. A static List holds a reference to an object you no longer need. What happens?

    Static fields are roots, so everything reachable from them stays alive. Clear or remove entries you no longer need, or use a bounded cache.
  5. 5. When is calling GC.Collect() in production code a good idea?

    Forced collections cost time and can promote short-lived objects. Use them in tests or benchmarks, and fix the allocation pattern or leak instead.

Summary

  • Objects live on the managed heap; allocation is a cheap pointer bump, and the GC pays for cleanup later.
  • The GC marks everything reachable from roots (locals, statics, handles) and reclaims the rest. Cycles are not a problem; accidental references from long-lived objects are.
  • Generations 0, 1 and 2 exploit the fact that most objects die young. Large objects (about 85,000 bytes and more) go to the large object heap, which is part of gen 2.
  • Finalizers delay reclamation and run on another thread at an unpredictable time. Use Dispose and SuppressFinalize instead.
  • WeakReference<T> watches an object without keeping it alive; always check TryGetTarget.
  • Workstation versus server GC and concurrent GC are configuration choices. Reduce allocations before tuning them, and avoid calling GC.Collect().

Next: Span, Memory and Slicing