wasAsked.

Generations in Garbage Collection

HCA Healthcare · Role not specified · technical

Published

Year not specified · C#

Community answers

Posted by wasAsked editorial collection

The .NET GC groups managed objects by age. New objects start in generation 0. Objects that survive a collection can be promoted to generation 1 and then generation 2. This generational design is efficient because most allocations die young, so Gen 0 can be collected frequently and cheaply while long-lived objects are scanned less often. Large objects normally go to the large object heap and are collected with Gen 2. ```csharp long before = GC.GetAllocatedBytesForCurrentThread(); var values = Enumerable.Range(0, 10_000).ToArray(); long allocated = GC.GetAllocatedBytesForCurrentThread() - before; Console.WriteLine($"Allocated: {allocated:N0} bytes"); ``` Generation is not an ownership mechanism, and calling `GC.Collect()` in normal application code is usually harmful because it disrupts the GC's adaptive decisions. Dispose unmanaged-resource wrappers promptly with `using`; disposal and garbage collection solve different problems. Diagnose with counters, traces, or dumps, then reduce proven high-volume allocations or unintended retention.

Prince Yadav · · 0 likes

Sign in to add your answer

Related interview topics