C# & CLR Internals (50 Qs)•Part 1: Core Language, CLR & Memory Architecture (1 - 10)
How does the .NET Garbage Collector work (Generations 0, 1, 2 and LOH)?
senior LevelMemory ManagementSystem Design
In Simple Words: The .NET Garbage Collector divides managed heap objects into 3 generations based on age, plus a Large Object Heap:
- Generation 0: Short-lived objects (temporary local variables). Collected most frequently in milliseconds.
- Generation 1: Buffer generation. Serves as a ramp between short-lived and long-lived objects.
- Generation 2: Long-lived objects (static singletons, application caches). Collected during full GC cycles.
- LOH (Large Object Heap): Objects >= 85,000 bytes. Avoided copying during compaction to prevent performance hit, but can be compacted via
GCSettings.LargeObjectHeapCompactionMode. - POH (Pinned Object Heap in .NET 5+): Dedicated heap for pinned objects to prevent heap fragmentation.