Senior · Explain · LOH allocation, fragmentation and compaction evidence

Why does 60 MiB of free heap space not prove a 40 MiB allocation can succeed?

Think through your answer before opening the explanation.

Memory & GC

Reveal answer and reasoning

When a large object becomes unreachable, reclaiming its space can leave a free region between live objects. A later allocation needs a suitable region or additional memory; a sum of scattered free bytes does not by itself establish that a sufficiently large contiguous object can fit. Fragmentation is therefore about the layout and distribution of available space, not simply a count of unreachable application values.

LOH participates in Gen 2 collection. Sweeping and compaction are distinct operations: reclaiming dead objects need not move every survivor, while compaction may relocate movable objects to change the layout. CoreCLR can support explicit LOH compaction requests, but pinned objects and runtime policy constrain movement. Neither operation changes a live application's semantic ownership. A strongly rooted large array remains live after a compacting full collection.

A heap can retain committed space ready for future allocations after some objects have died. Process resident memory additionally includes memory outside the managed heap, such as native allocations, stacks and runtime structures. It is consequently normal for application membership, managed live bytes, heap size including fragmentation, committed GC memory and working set to move differently. State which quantity a chart represents before interpreting it.

The desktop experiment prints GCMemoryInfo snapshots around controlled requests. Those fields describe the latest completed relevant collection rather than a continuous synchronized census of every process allocation. Calling the snapshot before a new collection can show an older GC index. The experiment records that index so comparisons can be qualified. It requests collection to make an isolated mechanism observable; production tuning must be assessed with normal workload behavior and latency evidence.

What a strong answer covers

  • The usual CoreCLR LOH threshold refers to total object size.
  • Free fragments, live bytes and committed memory measure different things.
  • Compaction changes layout, not the application ownership contract.

Common pitfall

Comparing an array payload length directly with the LOH object-size threshold, or equating free gaps with RSS.

Follow-up questions

  1. Why can chunking still lead to a final large concatenation allocation?
  2. Which GC index and fragmentation observations would you compare?

Self-review

Choose what to revisit. These marks are your own assessment and are separate from lesson completion.

Primary references

Open lesson and code ↗

← All interview questions