Free Space ≠ Wasted Space

When you see “free space” in the Garbage Collector (GC) heap, it’s not wasted.
This space, called fragmentation, comes from how the GC reclaims memory:

  • Sweeping → quick cleanup, leaves gaps
  • Compacting → full reorganization, removes gaps

Sweeping: The Quick Tidy-Up

  • Process:
    GC scans the heap, marks dead objects, and builds a free list (locations + sizes of gaps).
  • Result:
    Surviving objects stay where they are, heap size doesn’t shrink, gaps remain (fragmentation).
  • Analogy:
    Like walking past your bookshelf, noticing empty slots, and keeping track of them for new books.

Compacting: The Deep Reorganization

  • Process:
    GC moves all surviving objects together, updates their references, and leaves one large block of free memory.
  • Result:
    Heap becomes tightly packed with no fragmentation, but the process is slower.
  • Analogy:
    Like spending a weekend reorganizing your entire bookshelf — pulling everything out, sorting, and packing it neatly.

When is Each Used?

  • Sweeping → used by Background GC (BGC) to clean Gen 2 with minimal pauses.
  • Compacting → used during full GC when memory pressure is high and heap size must shrink.

Comparison Table

StrategySpeedMoves Objects?Shrinks Heap?Fragmentation?
Sweeping✅ Fast❌ No❌ No✅ Yes
Compacting❌ Slow✅ Yes✅ Yes❌ No