Course contentsShow
← Computer Science
Lesson 2097 of 2,87247. Memory Management in LanguagesFree lesson

Copying Collection

Divide heap into two spaces; copy live objects to the other space, then swap, leaving garbage behind.

Copying Collection

What you'll learn: How a copying garbage collector moves live objects to a fresh memory space, leaving all garbage behind in one efficient pass.

The Core Idea

Copying collection divides the heap into two equal halves (often called "from-space" and "to-space"). When garbage collection is triggered:

  1. Copy all live objects from the from-space to the to-space
  2. Update all references to point to the new locations
  3. Swap the roles of the two spaces (to-space becomes the new from-space)
  4. Reclaim everything left behind in the old from-space — it's all garbage

The beauty? You don't need to explicitly find and delete garbage. Anything not copied is automatically garbage.

Why This Works

Remember that reachability determines liveness. Starting from the root set (stack variables, globals), you trace through all reachable objects and copy each one exactly once to the fresh space. When you're done copying, the old space contains only unreachable objects — pure garbage.

The Analogy

Imagine moving to a new apartment. Instead of sorting through every item to decide what's trash, you simply pack and move only what you need. Everything left in the old apartment? That's garbage. The landlord clears it all at once when you leave.

Key Benefits

  • No fragmentation — objects are compacted as they're copied
  • Fast allocation — the free space is contiguous; just bump a pointer
  • Simple implementation — no need to track individual garbage objects

The Cost

You only get to use half your heap at any time, since the other half must stay empty as a copy destination.

Key Takeaway: Copying collection efficiently reclaims memory by evacuating live objects to fresh space and abandoning everything else as garbage, eliminating fragmentation in the process.