wasAsked.

Garbage collection — explain Gen 0, Gen 1, Gen 2.

Routeware · Role not specified · technical

Published

Year not specified · C#

Community answers

Posted by wasAsked editorial collection

The .NET GC divides the managed heap into generations because object lifetimes follow a pattern: most objects die young, and objects that survive tend to live long. Collecting young objects frequently and old objects rarely makes GC fast. Generation 0 - Where new small objects are allocated. - Small budget, collected very frequently. - Most temporary objects (strings built during a request, DTOs, LINQ iterators) die here, so a Gen 0 collection reclaims most garbage quickly — usually in a millisecond or less. - Objects that survive a Gen 0 collection are promoted to Gen 1. Generation 1 - A buffer between short-lived and long-lived objects. - Collected when Gen 0 collection does not free enough memory; a Gen 1 collection also collects Gen 0. - Survivors are promoted to Gen 2. Generation 2 - Long-lived objects: singletons, caches, static data, objects kept for the application's lifetime. - A Gen 2 collection is a full collection (Gen 0, 1, 2 plus the Large Object Heap) and is the most expensive. - Background GC lets most of a Gen 2 collection run concurrently with application threads to reduce pauses. Large Object Heap (LOH) - Objects of 85,000 bytes or more (large arrays and strings) are allocated directly here and logically belong to Gen 2. - Not compacted by default (compaction can be requested with GCSettings.LargeObjectHeapCompactionMode), so frequent large temporary allocations cause fragmentation. Use ArrayPool<T> or streaming to avoid them. Why it matters for performance - If many objects survive to Gen 2 and then die soon after (the "mid-life crisis" problem), you get expensive Gen 2 collections. Example: caching request data for a few minutes. - Monitoring Gen 0, 1 and 2 collection counts (dotnet-counters) shows whether a service has healthy GC behaviour: many Gen 0, fewer Gen 1, rare Gen 2. Quick demonstration: var obj = new object(); Console.WriteLine(GC.GetGeneration(obj)); // 0 GC.Collect(); Console.WriteLine(GC.GetGeneration(obj)); // 1 GC.Collect(); Console.WriteLine(GC.GetGeneration(obj)); // 2 (Use GC.Collect only for demonstrations like this, not in production code.)

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics