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
- Start at the roots (stack, globals)
- Mark every object reachable from them
- Sweep: free all unmarked objects
- 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 GCForce GC in Node (debug only)
node --expose-gc app.js
// global.gc()Tune the JVM
java -Xmx2g -XX:+UseG1GC -jar app.jarCommon 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.