10. Garbage Collection
Automatic memory management for language runtimes
Every value your program creates — numbers, strings, closures, arrays — takes up
memory. When a value is no longer needed, that memory should be reclaimed. You
can do this manually (malloc/free in C), but manual memory management is
notoriously error-prone: forget to free something and you leak memory; free it
too early and you get a use-after-free bug; free it twice and you corrupt the
heap.
Garbage collection (GC) automates this. The runtime periodically identifies which objects are still reachable and frees everything else. It's used by JavaScript, Python, Java, Go, Ruby, Lua, C#, and most modern languages.
The core idea: reachability
An object is alive if the running program could possibly access it. An object is garbage if no chain of references connects it to the program's active state.
The program's active state — the roots — includes:
- Local variables on the stack
- Global variables
- The current call frame chain
- Any temporary values the VM is working with
If you can reach an object by following references from a root, it's alive. If not, it's garbage. Simple as that.
let a = { name: "Alice" }; // reachable from global 'a'
let b = a; // also reachable from global 'b'
a = null; // still reachable from 'b'
b = null; // unreachable! — garbage
Reference counting
The simplest GC strategy: give every object a counter that tracks how many references point to it. When a reference is created, increment the count. When a reference is removed, decrement it. When the count hits zero, free the object.
class RcObject {
constructor(value) {
this.value = value;
this.refCount = 1;
}
}
function assign(target, source) {
if (source) source.refCount++;
if (target) {
target.refCount--;
if (target.refCount === 0) free(target);
}
return source;
}
Reference counting is appealingly simple:
- Memory is freed immediately when it becomes unreachable.
- No pauses — the work is spread across every assignment.
- Easy to implement.
But it has a fatal flaw: cycles.
let a = {};
let b = {};
a.ref = b; // a → b
b.ref = a; // b → a (cycle!)
a = null;
b = null;
// Both objects have refCount 1 (from each other)
// Neither will ever be freed!
Two objects pointing at each other keep each other's reference count above zero
forever, even though neither is reachable from the program. CPython uses
reference counting as its primary GC but adds a separate cycle detector to
handle this case. Swift uses reference counting with explicit weak references
to break cycles.
Mark-and-sweep
The most common tracing GC algorithm is mark-and-sweep. It runs in two phases:
Mark phase: Start from the roots. Follow every reference, marking each object you visit as "alive." This is a graph traversal — depth-first or breadth-first, it doesn't matter.
Sweep phase: Walk through every allocated object. If it's marked, unmark it (for next time) and keep it. If it's not marked, it's unreachable — free it.
class GC {
constructor() {
this.allObjects = []; // every allocated object
this.roots = []; // the VM's stack + globals
}
collect() {
this.mark();
this.sweep();
}
mark() {
const worklist = [...this.roots];
while (worklist.length > 0) {
const obj = worklist.pop();
if (obj.marked) continue;
obj.marked = true;
// Follow references inside this object
for (const ref of obj.references()) {
if (ref && !ref.marked) worklist.push(ref);
}
}
}
sweep() {
this.allObjects = this.allObjects.filter(obj => {
if (obj.marked) {
obj.marked = false; // reset for next cycle
return true; // keep
}
obj.free();
return false; // remove
});
}
}
Mark-and-sweep handles cycles naturally: if two objects point at each other but neither is reachable from a root, neither gets marked, and both get swept. The cycle problem simply doesn't arise.
The tri-color abstraction
It helps to think of objects in three states during marking:
- White: not yet visited — potentially garbage
- Gray: visited but its references haven't been fully traced yet
- Black: visited and all its references have been traced
The algorithm starts with all objects white, roots are colored gray, and the loop pulls gray objects off the worklist, traces their references (coloring newly found objects gray), and colors the processed object black. When no gray objects remain, every white object is garbage.
This tri-color invariant is the foundation for more advanced techniques like incremental and concurrent collection — you can pause between processing gray objects and resume later, as long as you maintain the invariant that black objects never point directly to white objects.
Stop-the-world pauses
The simplest mark-and-sweep implementation stops the program entirely while collecting. This is a stop-the-world pause. For small heaps, the pause is imperceptible. For large heaps, it can be hundreds of milliseconds — enough to cause visible stuttering in games or dropped frames in video playback.
Strategies to reduce pauses:
- Incremental GC: do marking in small steps interleaved with program execution
- Concurrent GC: run the collector on a separate thread while the program continues
- Generational GC: focus collection on young objects (see below)
Generational GC
Most objects die young. A string built for a log message, a temporary array in a sort function, a closure created for a single callback — these are allocated, used, and discarded almost immediately. Long-lived objects (global config, cached data, the DOM tree) are rare by comparison.
Generational GC exploits this observation by dividing the heap into two (or more) regions:
- Young generation (nursery): where new objects are allocated. Collected frequently with a fast "minor collection."
- Old generation (tenured): objects that survive several young-gen collections are "promoted" here. Collected rarely with a slower "major collection."
Young generation Old generation
┌─────────────────────────┐ ┌─────────────────────────┐
│ new objects land here │───>│ survivors promoted here │
│ collected frequently │ │ collected rarely │
└─────────────────────────┘ └─────────────────────────┘
minor GC (~1ms) major GC (~50ms)
Minor collections are fast because:
- The young generation is small (typically a few MB).
- Most objects in it are already dead.
- The collector only needs to copy the survivors — not touch the dead objects at all.
V8 (Chrome/Node.js), HotSpot (Java), and .NET all use generational collectors.
Adding GC to our bytecode VM
Let's connect a mark-and-sweep collector to the bytecode VM from earlier articles. The VM already has everything we need for roots:
class VM {
constructor() {
this.stack = []; // root: values on the stack
this.globals = {}; // root: global variables
this.frames = []; // root: call frames with closures
this.gc = new GC(this);
}
allocate(obj) {
// Register with the GC
this.gc.track(obj);
// Maybe trigger collection
if (this.gc.shouldCollect()) {
this.gc.collect();
}
return obj;
}
}
The GC needs to know how to find references inside each object type:
class GCObject {
constructor() {
this.marked = false;
}
references() { return []; } // override in subclasses
}
class ObjString extends GCObject {
constructor(value) {
super();
this.value = value;
}
references() { return []; } // strings have no outgoing refs
}
class ObjClosure extends GCObject {
constructor(func, upvalues) {
super();
this.func = func;
this.upvalues = upvalues;
}
references() {
return [this.func, ...this.upvalues];
}
}
class ObjArray extends GCObject {
constructor(elements) {
super();
this.elements = elements;
}
references() {
return this.elements.filter(e => e instanceof GCObject);
}
}
And the collector gathers roots from the VM and traces:
class GC {
constructor(vm) {
this.vm = vm;
this.objects = [];
this.bytesAllocated = 0;
this.nextGC = 1024; // collect after 1KB allocated
}
shouldCollect() {
return this.bytesAllocated > this.nextGC;
}
track(obj) {
this.objects.push(obj);
this.bytesAllocated += obj.size || 8;
}
collect() {
const before = this.objects.length;
// Gather roots from the VM
this.markRoots();
this.traceReferences();
this.sweep();
// Grow the threshold to avoid collecting too often
this.nextGC = this.bytesAllocated * 2;
}
markRoots() {
// Stack values
for (const val of this.vm.stack) {
if (val instanceof GCObject) this.markObject(val);
}
// Globals
for (const val of Object.values(this.vm.globals)) {
if (val instanceof GCObject) this.markObject(val);
}
// Closure upvalues in call frames
for (const frame of this.vm.frames) {
if (frame.closure) this.markObject(frame.closure);
}
}
markObject(obj) {
if (!obj || obj.marked) return;
obj.marked = true;
this.grayStack.push(obj);
}
traceReferences() {
this.grayStack = this.grayStack || [];
while (this.grayStack.length > 0) {
const obj = this.grayStack.pop();
for (const ref of obj.references()) {
this.markObject(ref);
}
}
}
sweep() {
this.objects = this.objects.filter(obj => {
if (obj.marked) {
obj.marked = false;
return true;
}
this.bytesAllocated -= (obj.size || 8);
return false;
});
}
}
When to collect
The collector runs during allocation — specifically, when the total allocated bytes exceed a threshold. After each collection, the threshold is doubled (or scaled by a factor). This means the GC runs more often when the program is allocating heavily and less often when it's not.
Some VMs also trigger collection at specific points:
- End of a function call (a natural "safe point" where the stack is in a known state)
- When the program is idle (requestIdleCallback in browsers)
- When the OS signals memory pressure
The tradeoff space
Every GC strategy trades off between several axes:
| Reference counting | Mark-and-sweep | Generational | |
|---|---|---|---|
| Pause time | None (amortized) | Stop-the-world | Short (minor) + rare long (major) |
| Throughput | Overhead on every assignment | Good (batch work) | Best (most work skipped) |
| Cycles | Cannot handle (needs backup) | Handles naturally | Handles naturally |
| Complexity | Low | Medium | High |
Production languages often combine techniques. CPython uses reference counting with a cycle detector. Java uses generational collection with concurrent marking. Go uses a concurrent tri-color collector.
Why this matters for language builders
If you're building a language — even a toy one — you'll hit the memory question as soon as you add closures, strings, or any heap-allocated data. Without a GC, you need to manually track every allocation's lifetime, which is error-prone and limits what your language can express.
Adding a simple mark-and-sweep collector like the one above is straightforward and lets your language handle arbitrarily complex object graphs — closures referencing closures, arrays of arrays, circular data structures — without any special effort from the programmer.
That's the entire series arc: we started with raw text and a tokenizer, built a parser, constructed ASTs, walked them to evaluate programs, compiled to bytecode, added scoping and closures, type checking, and finally automated memory management. You now have the complete skeleton of a real programming language.
Try It Yourself — GC Visualizer
Write a program that allocates objects. Watch the mark phase trace from roots through the object graph, then see the sweep phase reclaim unreachable objects. The visualization shows which objects are roots, which are reachable via reference chains, and which get collected.