Garbage collection and generations
Understanding how .NET manages memory is crucial for writing efficient and stable applications, avoiding memory leaks, and optimizing performance.
Automatic memory management
The .NET Common Language Runtime (CLR) has an automatic garbage collector (GC) that manages the allocation and release of memory for managed objects. Developers generally don’t need to allocate or deallocate memory manually.
The managed heap
When you create an object with new, memory is allocated for it on the managed heap. The GC periodically reclaims the memory of objects that are no longer reachable, or referenced, by the application.
Generations
The .NET GC uses a generational collection strategy to optimize performance. The managed heap is divided into, typically, three generations:
- Generation 0 (Gen 0) is where newly allocated, short-lived objects live. Gen 0 collections are frequent and fast, because they target a small portion of the heap. Most objects are reclaimed in Gen 0.
- Generation 1 (Gen 1) receives the objects that survive a Gen 0 collection. It acts as a buffer between short-lived and long-lived objects. Gen 1 collections are less frequent than Gen 0.
- Generation 2 (Gen 2) receives the objects that survive a Gen 1 collection, and contains long-lived objects. Gen 2 collections are full garbage collections, meaning they scan the entire managed heap. They are the most time-consuming and occur least frequently.
This generational approach is based on the empirical observation that most objects die young.
The Large Object Heap (LOH)
Objects larger than a certain threshold, currently 85,000 bytes, are allocated on a special segment of the heap called the Large Object Heap (LOH). It is managed differently from the generational heaps. It is typically not compacted, to avoid the cost of moving large blocks of memory. That can lead to memory fragmentation if many large objects with varying lifetimes are allocated and deallocated. Frequent LOH allocations can also trigger more frequent full Gen 2 collections.
The GC only knows about managed memory. For files, connections and other unmanaged resources, see IDisposableIDisposable and the Dispose patternHow to release the resources the garbage collector does not know about.Opens in a new tab.
Sources
- .NET Framework, Wikipedia · accessed May 16, 2025
- Advanced Memory Management Techniques in C#, TechOnDiapers · accessed May 16, 2025