Skip to content

Garbage Collector and Heaps

Question

Explain the garbage collector, small object heap, and large object heap.

Short interview answer

The .NET garbage collector reclaims managed objects that are unreachable from application roots. It is generational: short-lived objects begin in generation 0, while long-lived objects advance to older generations. Large allocations use the large object heap and are collected with generation 2.

Detailed answer

The GC starts from roots such as active stack references, static fields, and handles, then follows references. Objects it cannot reach are eligible for collection. For example, after var report = new Report(); leaves scope, the object can be collected only if nothing else—such as a cache or event subscription—still refers to it. That is why “the variable went out of scope” is not a release guarantee.

Most allocations are ordinary small-object allocations. An allocation of 85,000 bytes or more goes to the large object heap (LOH). A byte[100_000] is therefore a LOH allocation; repeatedly allocating such buffers for request processing can force more expensive collections and fragment memory. The answer is not to call GC.Collect(): reuse or pool buffers only after measurement, and first remove unnecessary retention. The GC manages memory; it does not close files, return database connections, or release native handles promptly.

Sources