What Is Garbage Collection?

Garbage collection is an automatic memory management process that identifies objects a program no longer references and reclaims their memory, without the de...

Published October 7, 2026

Garbage collection (GC) automatically finds memory that a program can no longer reach and frees it, so developers do not call free() manually. Languages like Java, JavaScript, Python and Go rely on it.

The concept

A garbage collector starts from 'roots' (global variables, the stack) and marks everything reachable. Unmarked objects are garbage and are reclaimed.

Python also uses reference counting. GC runs can pause the program briefly, so modern collectors are generational and concurrent.

Mark and sweep

  1. Start at the roots (stack, globals)
  2. Mark every object reachable from them
  3. Sweep: free all unmarked objects
  4. Memory becomes available for new allocations

Practical examples

Making an object collectible

let big = new Array(1e6).fill(0)
big = null   // no references left → eligible for GC

Force GC in Node (debug only)

node --expose-gc app.js
// global.gc()

Tune the JVM

java -Xmx2g -XX:+UseG1GC -jar app.jar

Common mistakes

  • Assuming GC prevents all leaks (live references still leak).
  • Calling GC manually in production.
  • Creating huge temporary objects in hot loops.

Key takeaways

  • GC frees unreachable memory.
  • Leaks still happen through lingering references.
  • Tune only when profiling shows a problem.

FAQ

Does GC make programs slow?

It adds overhead and brief pauses, mitigated by modern collectors.

What about Rust and C++?

They manage memory with ownership or manual control instead.

More General articles