Every language I write at work has a garbage collector. TypeScript on Node, Go, Python. I've
never called free() in production code, and for a long time my mental model of what replaces
it was one sentence: "the runtime frees memory you aren't using any more."
That sentence is wrong in a small way and incomplete in a big one. The runtime can't know what you aren't using. It only knows what you can still reach. And "frees" hides the actual engineering: how do you find every live object in a multi-gigabyte heap while forty threads are rewriting pointers underneath you, without stopping the world for half a second?
So I went and read the papers and the runtime source docs. This is the version of the answer I wish I'd had years ago: not "what is GC," but how the collectors I depend on actually work, and why they behave the way they do in production.
🎯 What a Garbage Collector Actually Promises
A garbage collector does two jobs: it allocates memory, and it reclaims memory that the program can provably never touch again. The second job needs a definition of "never touch again," and every production GC uses the same conservative approximation:
An object is live if it is reachable from a root by following pointers.
The roots are the places the program can read a pointer from without first going through another heap object:
- Stacks: local variables and spilled registers of every thread
- Registers: pointers held in CPU registers at the moment of collection
- Globals and statics: module-level variables, class statics
- Runtime handles: JIT-compiled code constants, interned strings, handles held by native code
Everything reachable from those roots is live. Everything else is garbage. That's the whole contract.
Notice what this does and doesn't cover. An object you'll never use again, but that is still
referenced from a global Map, is live by this definition. A GC has no idea about your
intentions. It frees unreachable memory, not unused memory. That gap is where every
"memory leak in a garbage-collected language" lives.
📜 A Very Short History
GC is older than most of the languages that use it:
| Year | Idea | Who |
|---|---|---|
| 1960 | Mark-sweep tracing, for Lisp | John McCarthy |
| 1960 | Reference counting | George Collins |
| 1969 | Semi-space copying collection | Fenichel & Yochelson |
| 1970 | Non-recursive copying (BFS) | C. J. Cheney |
| 1978 | Tri-colour concurrent marking | Dijkstra, Lamport et al. ("On-the-fly") |
| 1983 | Generational collection | Lieberman & Hewitt; Ungar (1984) |
| 1990s+ | Incremental, parallel, concurrent, regional collectors | HotSpot, V8, Go, .NET … |
Almost everything in a modern collector is a refinement of those first six rows. ZGC's coloured pointers, Go's hybrid write barrier and V8's parallel scavenger are all engineering on top of ideas from before 1985.
🧮 The Two Families: Tracing vs Reference Counting
There are two fundamentally different ways to decide liveness.
Reference counting
Every object carries a counter of how many pointers point at it. Storing a pointer increments the target's count; overwriting or dropping one decrements it. When a count hits zero, the object is freed immediately, and its own outgoing pointers are decremented in turn.
a = N o d e ( ) # N o d e . r c = 1
b = a # N o d e . r c = 2
d e l a # N o d e . r c = 1
b = N o n e # N o d e . r c = 0 → f r e e d r i g h t h e r e , d e t e r m i n i s t i c a l l y
What's good about it:
- Reclamation is immediate and incremental. No big pause to "find" garbage; it's freed the moment it becomes garbage (modulo cascades: freeing the head of a million-node linked list frees a million nodes, right now).
- Cost is proportional to pointer mutation, not heap size.
- Destruction is deterministic, which is why CPython closes your file the instant the last reference disappears, and why Swift and Objective-C use it (ARC).
What's bad about it:
- Cycles never reach zero.
a.next = b; b.next = aand both counts stay at 1 forever, even after nothing else references either. Every RC system needs a separate cycle collector or weak references. - Every pointer write becomes a memory write elsewhere. Even reading a pointer into a local often needs an increment/decrement pair. That's cache traffic on objects you didn't otherwise touch.
- Multithreading makes it expensive. Counts must be updated atomically, and atomic read-modify-write on shared cache lines is slow. This is a big part of why CPython had a GIL for so long, and why free-threaded CPython uses biased reference counting (cheap non-atomic increments for the owning thread, atomic only for others).
Tracing
Tracing collectors ignore pointer writes (mostly) and instead periodically compute the reachable set from scratch: start at the roots, follow every pointer, mark what you find. Whatever wasn't found is garbage.
The cost model is the inverse of RC:
- Mutation is nearly free. A pointer store is just a store (plus a barrier during concurrent phases, more on that later).
- Cycles are a non-issue. An unreachable cycle is simply never visited.
- Reclamation is deferred and batched. Garbage sits around until the next cycle, and the work arrives in bursts, which is where pauses come from.
Bacon, Cheng and Rajan's 2004 paper A Unified Theory of Garbage Collection makes the relationship precise: tracing computes liveness from the live side, RC computes it from the dead side, and every real collector (deferred RC, generational tracing with remembered sets) is a hybrid somewhere on the line between them. That framing is worth keeping in mind, because it explains why CPython (RC plus a tracing cycle collector) and the JVM (tracing plus RC-like remembered sets) end up looking more similar than you'd expect.
The rest of this post is mostly about tracing, because that's what V8, Go, the JVM and .NET use.
🧹 Three Ways to Reclaim: Sweep, Copy, Compact
Marking tells you what's alive. You still have to turn the dead space into reusable memory, and there are three classic strategies.
Mark-sweep
Mark live objects, then walk the heap linearly and put every unmarked block on a free list.
B e f o r e : [ A ] [ x ] [ B ] [ x ] [ x ] [ C ] [ x ] [ D ] x = d e a d
A f t e r : [ A ] [ ] [ B ] [ ] [ C ] [ ] [ D ] f r e e l i s t : 3 h o l e s o f d i f f e r e n t s i z e s
- Non-moving: pointers never change, which makes interop with C and conservative stack scanning easy.
- Fragmentation: you can have 500 MB free and still fail to allocate a 2 MB array because no single hole is large enough. Allocation needs size-segregated free lists, which is slower than bumping a pointer.
- Sweep cost is proportional to heap size, not live size. Most runtimes sweep lazily (on allocation) or concurrently to hide it.
Copying (semi-space)
Split the space in two. Allocate only in from-space. To collect, copy every reachable object into to-space, then flip the roles. Everything left in from-space is garbage, discarded without being looked at.
Cheney's 1970 algorithm does this without recursion, using to-space itself as the BFS queue:
s c a n f r e e
▼ ▼
t o - s p a c e : [ A ' ] [ B ' ] [ C ' ] [ . . . ]
1 . C o p y e a c h r o o t ' s t a r g e t i n t o t o - s p a c e a t ` f r e e ` , b u m p ` f r e e ` .
2 . L e a v e a f o r w a r d i n g p o i n t e r i n t h e o l d c o p y : A → A ' .
3 . W h i l e s c a n < f r e e :
f o r e a c h p o i n t e r f i e l d i n o b j e c t a t ` s c a n ` :
i f t a r g e t a l r e a d y f o r w a r d e d : r e w r i t e f i e l d t o t h e f o r w a r d i n g a d d r e s s
e l s e : c o p y t a r g e t t o ` f r e e ` , f o r w a r d i t , r e w r i t e f i e l d
s c a n + = s i z e o f t h a t o b j e c t
Why this matters:
- Cost is proportional to live data only. Dead objects are never touched. If 98% of a space is garbage, collection is almost free.
- Allocation is a bump pointer:
obj = free; free += size. A few instructions, no free lists, perfect locality. - No fragmentation, ever. Survivors end up packed together, in BFS order.
- You waste half the memory, and you must be able to find and rewrite every pointer to a moved object. That second requirement (precise knowledge of where pointers are) has deep consequences, covered below.
Mark-compact
Mark, then slide live objects together inside the same space and update every pointer. You get copying's compactness without the 2× space overhead, at the cost of several passes over the heap (compute new addresses, update references, move). The JVM's old-generation collectors and V8's old space use variants of this, often compacting only the most fragmented pages instead of the whole heap.
| Strategy | Work proportional to | Moves objects | Fragmentation | Space overhead |
|---|---|---|---|---|
| Mark-sweep | Live (mark) + heap (sweep) | No | Yes | Low |
| Copying | Live only | Yes | None | 2× the space |
| Mark-compact | Live + heap (multiple passes) | Yes | None | Low |
Real collectors mix all three: copy the young objects, mark-sweep most of the old ones, compact the old pages that have become too fragmented.
👶 The Generational Hypothesis
Measure almost any program and you find the same distribution: most objects die young. Request-scoped objects, temporary strings, iterator state, closures for a single callback. The weak generational hypothesis says the vast majority of allocations become unreachable shortly after they're created.
Combine that with copying's cost model (pay only for survivors) and you get the single most important optimisation in production GC:
┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ Y o u n g g e n e r a t i o n ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ ┌ ─ ─ ─ ─ O l d g e n e r a t i o n ─ ─ ─ ─ ┐
│ E d e n / n u r s e r y │ S u r v i v o r │ S u r v i v o r │ │ │
│ b u m p - p o i n t e r a l l o c s │ ( f r o m ) │ ( t o ) │ ─ ─ ▶ │ m a r k - s w e e p / c o m p a c t │
│ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ │ ▒ ▒ ▒ │ │ │ c o l l e c t e d r a r e l y │
└ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘ └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘
m i n o r G C : c o p y s u r v i v o r s o u t , d i s c a r d t h e r e s t p r o m o t e d a f t e r N s u r v i v a l s
- Minor GCs collect only the young generation. They're frequent, fast and cheap, because the young space is small and almost everything in it is dead.
- Objects that survive a few minor GCs are promoted (tenured) into the old generation.
- Major GCs collect the old generation. They're rare and expensive.
The catch: old-to-young pointers
A minor GC only traces the young generation. But an old object can point at a young one:
c o n s t c a c h e = n e w M a p ( ) ; / / a l l o c a t e d l o n g a g o , n o w i n o l d s p a c e
c a c h e . s e t ( k e y , { f r e s h : t r u e } ) ; / / b r a n d - n e w o b j e c t , i n y o u n g s p a c e
If the minor GC only starts from the stacks, it never sees cache's pointer and frees a live
object. Scanning the whole old generation to find such pointers would defeat the point of a
cheap minor GC.
The fix is a write barrier: a small piece of code the compiler inserts on every pointer store into the heap.
/ / c o n c e p t u a l l y , f o r : o b j . f i e l d = v a l u e
o b j - > f i e l d = v a l u e ;
i f ( i s _ o l d ( o b j ) & & i s _ y o u n g ( v a l u e ) )
r e m e m b e r ( o b j , & o b j - > f i e l d ) ; / / r e c o r d t h e o l d → y o u n g e d g e
The recorded edges form the remembered set, which minor GCs treat as extra roots. HotSpot uses a cheaper, coarser variant called a card table: the heap is divided into 512-byte "cards," each with one byte in a side table. The barrier unconditionally dirties the card containing the written field (a shift and a byte store, no branches), and the minor GC scans only dirty cards.
This is the first place GC costs leak into your code's hot path. Every pointer store your program executes pays for that barrier, whether a GC is running or not.
🎨 Tri-Colour Marking and the Lost Object Problem
Stop-the-world (STW) marking is easy to get right: pause every thread, trace, resume. But the pause is proportional to the live heap, and a few gigabytes of live objects means hundreds of milliseconds. Modern collectors instead mark concurrently, while the program (the mutator, in GC literature) keeps running. That's where it gets subtle.
The standard model is Dijkstra's tri-colour abstraction:
- ⚪ White: not yet seen. At the end of marking, white means garbage.
- 🔘 Grey: seen, but its outgoing pointers haven't been scanned yet. The work list.
- ⚫ Black: seen, and all its children have been pushed. Done.
Marking starts with roots grey, repeatedly takes a grey object, greys its white children and blackens it, and finishes when no grey remains.
Now let the mutator run at the same time. Two things happen in sequence:
1 . M u t a t o r s t o r e s a p o i n t e r t o w h i t e o b j e c t W i n t o b l a c k o b j e c t B .
B ( b l a c k ) ─ ─ ─ ─ ─ ─ ─ ▶ W ( w h i t e ) B h a s a l r e a d y b e e n s c a n n e d ; t h e G C w o n ' t l o o k a g a i n
2 . M u t a t o r d e l e t e s t h e o n l y o t h e r p a t h t o W , f r o m g r e y o b j e c t G .
G ( g r e y ) ─ ─ ─ ╳ ─ ─ ─ ▶ W
The collector finishes, W is still white, and it gets freed, while B still points at it. That's a use-after-free produced by the garbage collector itself, the worst bug a runtime can ship.
The lost object problem needs both conditions at once:
- A black object gains a pointer to a white object, and
- Every path from a grey object to that white object is destroyed.
Concurrent collectors stay correct by using a barrier to break one of the two.
Insertion barrier (Dijkstra, 1978): break condition 1
On every pointer store, shade the new target grey:
w r i t e ( s l o t , p t r ) :
s h a d e ( p t r ) / / i f p t r i s w h i t e , m a k e i t g r e y
* s l o t = p t r
A black object can never point to a white one. This maintains the strong tri-colour invariant. The cost: stacks usually aren't barriered (too expensive), so stacks can't be treated as black, and must be re-scanned in a final STW pause.
Deletion barrier (Yuasa, 1990): break condition 2
On every pointer store, shade the old target before overwriting it:
w r i t e ( s l o t , p t r ) :
s h a d e ( * s l o t ) / / w h a t e v e r w e ' r e a b o u t t o d r o p g e t s k e p t a l i v e
* s l o t = p t r
Nothing reachable when marking began can be lost. This is snapshot-at-the-beginning (SATB): the collector effectively marks the object graph as it existed at the start of the cycle, plus anything allocated since (new objects are allocated black). It's conservative (some objects that die mid-cycle survive until the next one) but it needs no stack re-scan. HotSpot's G1 and Shenandoah use SATB.
Go's hybrid barrier
Go used a Dijkstra barrier until Go 1.8, and its final stack re-scan was the dominant source of pause time for programs with many goroutines. Go 1.8 switched to a hybrid of both:
w r i t e ( s l o t , p t r ) :
s h a d e ( * s l o t ) / / Y u a s a : p r o t e c t w h a t ' s b e i n g r e m o v e d
i f c u r r e n t s t a c k i s g r e y :
s h a d e ( p t r ) / / D i j k s t r a : p r o t e c t w h a t ' s b e i n g i n s e r t e d
* s l o t = p t r
Stacks are scanned once, at the start of the cycle, goroutine by goroutine, and never re-scanned. That's the change that brought typical Go pause times from milliseconds down to well under one.
🧭 Finding the Roots: Safepoints and Stack Maps
"Scan the stacks" sounds simple until you remember that a stack is just bytes. Is that 8-byte
value at rsp+24 a pointer to an object, or an integer that happens to look like one?
There are two answers.
Precise (exact) GC. The compiler records stack maps: for specific instruction addresses, which stack slots and registers hold live pointers. The runtime can only use those maps at those addresses, so threads must be stopped at safepoints: function calls, loop back-edges, allocation sites. To stop the world, the runtime raises a flag (or protects a polling page so the next poll faults) and waits for every thread to reach its next safepoint.
That's why "time to safepoint" is its own latency problem. A tight counted loop with no
safepoint poll can delay a pause for the whole process. The JVM used to elide polls in
counted int loops for speed, which made this a real production issue until loop strip-mining
arrived. Go had the same problem: a tight loop could block GC indefinitely until Go 1.14 added
asynchronous preemption via signals.
Conservative GC. Treat any word on the stack that looks like a pointer into the heap as one. No compiler cooperation needed, which is why the Boehm collector can add GC to plain C. The price: you can't move an object that a conservative root might point at (you can't rewrite a value you aren't sure is a pointer), and the occasional integer will keep garbage alive. Some engines split the difference: JavaScriptCore scans stacks conservatively but treats heap objects precisely.
Moving collectors, which is to say generational and compacting ones, essentially require precise roots.
🏃 Concurrent Compaction: Moving Objects While They're in Use
Concurrent marking is solved. Concurrent moving is harder: if the collector relocates an object while a mutator thread holds a pointer to the old copy, one of them will read stale data. Until about 2018, mainstream collectors compacted in STW pauses, so pause time still scaled with the amount of data moved.
The fix is a read barrier (or load barrier): code on every pointer load from the heap that checks whether the object has moved and, if so, fixes the reference before the mutator uses it.
ZGC: coloured pointers
ZGC stores GC metadata in otherwise unused bits of the pointer itself. A load barrier checks those bits on every reference loaded from the heap:
6 3 ~ 4 6 c o l o u r b i t s 0
┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┬ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┬ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
│ u n u s e d │ m a r k e d / r e m a p │ o b j e c t a d d r e s s │
└ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┴ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┴ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘
l o a d ( r e f ) :
i f r e f h a s t h e " b a d " c o l o u r f o r t h e c u r r e n t p h a s e : / / f a s t p a t h : o n e t e s t + b r a n c h
r e f = s l o w _ p a t h ( r e f ) / / m a r k i t , o r l o o k u p i t s n e w a d d r e s s a n d r e m a p
h e a l t h e f i e l d i n p l a c e , s o t h e n e x t l o a d t a k e s t h e f a s t p a t h
r e t u r n r e f
Because the mutator itself fixes stale references as it encounters them ("self-healing"), the collector can relocate objects concurrently. STW pauses only cover root scanning and phase changes, and they don't grow with heap size: ZGC targets sub-millisecond pauses on heaps from megabytes to terabytes. Since JDK 21 it's also generational, and since JDK 24 that's the only mode.
Shenandoah: forwarding through the object
Shenandoah takes a different route to the same place. It originally gave every object an extra Brooks forwarding pointer word; today it uses a load reference barrier that resolves a forwarded object through its header. Same result: concurrent evacuation, pauses independent of heap size.
The price of both is throughput. A load barrier on every reference load costs far more in aggregate than a store barrier, because programs load pointers far more often than they store them. You trade a few percent of CPU for removing the pause.
⚙️ How Real Runtimes Pay the Bill
V8 (Node.js, Chrome): Orinoco
V8's heap is split into a young generation and an old generation, plus special spaces for code and large objects.
- Young generation: the Scavenger. A semi-space copying collector in the Cheney style, parallelised across helper threads. Objects that survive two scavenges are promoted to old space. Scavenges are short STW pauses, typically around a millisecond or two, because the young space is small and mostly dead.
- Old generation: Mark-Compact. Marking is mostly concurrent on background threads, with incremental steps on the main thread and a short final pause. Sweeping runs concurrently; compaction runs in parallel and only targets fragmented pages.
- Idle-time GC. In Chrome, V8 schedules GC work into idle periods between frames, so it doesn't steal time from a 16 ms frame budget.
What this means for a Node service: --max-old-space-size sets the old generation's limit, and
the young generation is sized much smaller by default. A workload that allocates heavily
per-request (large JSON parse/stringify, big intermediate arrays) can promote objects that were
almost dead, just because they were still alive during two scavenges. Raising
--max-semi-space-size gives them longer to die young, and it's one of the few V8 flags that
regularly pays for itself in throughput-heavy services. node --trace-gc shows you each
scavenge and mark-compact with its pause time.
Go: concurrent, non-moving, non-generational
Go made a deliberately unusual choice: no generations and no compaction. Its collector is a concurrent tri-colour mark-sweep with the hybrid write barrier above.
Why skip the industry's biggest optimisation? Because Go's compiler does escape analysis:
values that provably don't outlive their function are allocated on the stack, and never become
GC work at all. Go also has value types, so a []Point is one contiguous allocation rather than
an array of pointers to boxed objects. A large share of what would be young-generation garbage
in Java never reaches the Go heap. And a non-moving heap keeps cgo interop and pointer handling
simple.
The knobs are about when to collect, not how:
GOGC(default 100): start the next cycle when the heap has grown by 100% of the live heap from the last cycle. Live 200 MB → next GC at about 400 MB. Higher means fewer GCs and more memory.GOMEMLIMIT(Go 1.19+): a soft total-memory ceiling. As the process nears it, the GC runs more often regardless ofGOGC. The common container setting isGOMEMLIMITat ~90% of the container limit, sometimes withGOGC=offso that the limit alone drives collection.- The pacer decides when to start a cycle so marking finishes before the heap hits the target. If the program allocates faster than the GC can mark, goroutines that allocate are conscripted into mark assists: they have to do marking work before their allocation returns. That shows up as latency in request handlers, not as a "GC pause," which makes it easy to miss.
Go 1.25 shipped an experimental collector called Green Tea (GOEXPERIMENT=greenteagc) that
scans memory a span (page) at a time instead of chasing individual pointers. The goal is better
cache locality during marking, which is where Go's GC has spent most of its CPU.
GODEBUG=gctrace=1 prints a line per cycle with heap sizes, CPU split and wall time.
The JVM: a menu instead of a collector
HotSpot ships several collectors, because no single one wins every workload:
| Collector | Design | Optimises for |
|---|---|---|
| Serial | Single-threaded, generational, STW | Tiny heaps, containers |
| Parallel | Multi-threaded, generational, STW | Throughput (batch jobs) |
| G1 (default) | Regional, generational, SATB concurrent marking | Balanced, pause-time target |
| ZGC | Regional, generational, concurrent compaction (load barriers) | Sub-ms pauses |
| Shenandoah | Regional, concurrent compaction | Low pauses |
G1 is the interesting middle ground. It divides the heap into equal regions (1–32 MB).
Any region can be eden, survivor or old at any time. Old-to-young and cross-region pointers are
tracked by per-region remembered sets fed by the card table. After concurrent marking, G1
knows how much garbage each region holds, and in mixed collections it evacuates the regions
with the most garbage first (hence the name: "Garbage-First"), choosing how many to collect so
it stays within -XX:MaxGCPauseMillis. It's a pause-time goal, not a guarantee.
CPython: reference counting plus a cycle collector
CPython is the odd one out: reference counting does nearly all the work. Every PyObject
starts with ob_refcnt, and Py_INCREF/Py_DECREF are everywhere in the interpreter. Most
objects are freed the instant their last reference disappears.
A separate cycle collector handles cycles. It only tracks container objects (lists, dicts, class instances; not ints or strings), and finds cycles with a neat trick: for each tracked object, copy its refcount, then subtract one for every reference coming from another tracked object in the same set. Whatever still has a count above zero is referenced from outside (a root), so it's alive along with everything it reaches. The rest is an unreachable cycle. Python 3.14 made this collector incremental, which sharply reduces the worst-case pause on large heaps.
A production story shows the trade-off well. Instagram runs Django under a pre-fork server: a
master process loads the app, then fork()s workers that share its memory pages copy-on-write.
But reference counting writes to every object it touches, and so does the cycle collector's
bookkeeping. Merely reading a shared object dirtied its page and forced a private copy, so the
memory sharing quietly evaporated. Instagram's fix (2017) was to disable the cycle GC entirely,
and the follow-up was gc.freeze() in Python 3.7: move every object that exists before the
fork into a permanent generation the collector never scans.
🦀 Rust: Moving the Work to Compile Time
Rust takes the question every collector answers at runtime, "is this object still live?", and answers it at compile time instead. There's no collector, no heap scan, no barrier and no pause. Liveness isn't computed from reachability; it's decided by scope, and the compiler proves that the two never disagree.
Ownership: a reference count that is always 1
Every value has exactly one owner. When the owner goes out of scope, the value is dropped:
the compiler inserts the call to its destructor (Drop) and the deallocation at that point,
statically. Assigning or passing the value moves ownership, and the old binding becomes
unusable.
f n m a i n ( ) {
l e t a = S t r i n g : : f r o m ( " h e a p " ) ; / / ` a ` o w n s a h e a p b u f f e r
l e t b = a ; / / o w n e r s h i p m o v e s t o ` b ` ; u s i n g ` a ` i s n o w a c o m p i l e e r r o r
{
l e t r = & b ; / / a b o r r o w : n o o w n e r s h i p , n o c o u n t , n o r u n t i m e c o s t
p r i n t l n ! ( " { r } " ) ;
} / / ` r ` e n d s ; n o t h i n g t o f r e e
} / / ` b ` g o e s o u t o f s c o p e → d r o p ( b ) → b u f f e r f r e e d h e r e
In the terms of the earlier sections, an owned value is reference counting where the count is always exactly 1, so it never needs to be stored or updated. The "decrement to zero" happens at a point the compiler already knows. When a move happens on only one branch, the compiler adds a hidden drop flag on the stack and checks it at the end of the scope. That's the only runtime trace ownership leaves.
Borrowing: what makes it safe
Owning values isn't new; C++ has had RAII and unique_ptr for decades. What Rust adds is the
borrow checker, which rules out the bug a GC exists to prevent: using memory after it has
been freed.
- A reference (
&Tor&mut T) borrows a value without owning it. - Every reference has a lifetime, and the compiler rejects any program where a reference could outlive its owner. A dangling pointer is a compile error, not a crash.
- At any moment you can have many shared
&Tor one exclusive&mut T, never both. That aliasing rule is also what makes data races a compile error.
f n l o n g e s t < ' a > ( x : & ' a s t r , y : & ' a s t r ) - > & ' a s t r {
i f x . l e n ( ) > y . l e n ( ) { x } e l s e { y }
} / / t h e r e s u l t c a n ' t o u t l i v e e i t h e r i n p u t ; t h e c o m p i l e r c h e c k s e v e r y c a l l e r
A tracing GC makes use-after-free impossible by keeping everything reachable alive. Rust makes it impossible by refusing to compile any program where a reference could outlive what it points to.
When one owner isn't enough: Rc, Arc and Weak
Some data genuinely has several owners: a shared cache, a node in a graph, a config handle used by many tasks. For those, Rust gives you opt-in reference counting, in the standard library rather than the runtime:
| Type | Count | Use |
|---|---|---|
Box<T> |
none | Single owner on the heap |
Rc<T> |
non-atomic | Shared ownership within one thread |
Arc<T> |
atomic | Shared ownership across threads |
Weak<T> |
not owning | A back-pointer that doesn't keep the value alive |
The type system enforces the cost split from the reference-counting section. Rc uses cheap,
non-atomic increments, and the compiler won't let it cross a thread boundary (it isn't Send).
Arc pays for atomics only where you asked for them. You only pay reference-counting costs on
the values you chose to share, not on every pointer in the program.
And RC's old weakness is still there: cycles leak. Two Rcs pointing at each other never
reach zero. Rust's answer is the same as everyone else's: make one direction a Weak.
u s e s t d : : c e l l : : R e f C e l l ;
u s e s t d : : r c : : { R c , W e a k } ;
s t r u c t N o d e {
p a r e n t : R e f C e l l < W e a k < N o d e > > , / / u p : d o e s n ' t o w n , s o n o c y c l e
c h i l d r e n : R e f C e l l < V e c < R c < N o d e > > > , / / d o w n : o w n s
}
A detail worth knowing: in Rust, leaking memory is safe. std::mem::forget and
Box::leak are ordinary safe functions. Rust guarantees you'll never touch freed memory. It
doesn't promise that everything will eventually be freed.
Arenas: Rust's version of "free it all at once"
Cyclic, pointer-heavy structures (graphs, ASTs, ECS worlds, DOM trees) fight the borrow checker. The idiomatic way out looks a lot like a GC region:
- Arenas (
bumpalo,typed-arena) bump-allocate many objects and free them all together when the arena is dropped. That's the semi-space idea without the copying: allocation is a pointer bump, and deallocation is one operation for the whole batch. - Index-based graphs (
slotmap,petgraph) store nodes in aVecand use integer indices instead of pointers. Cycles become harmless, because an index doesn't own anything.
And when a program really does need a tracing GC (a language runtime, a scripting engine),
it's built as a library: crates like gc-arena provide garbage-collected pointers that are
confined to a scope the borrow checker can reason about.
What Rust pays instead
Rust doesn't make memory management free. It moves the costs somewhere else:
- Developer time and compile time. The borrow checker rejects programs that are actually
correct, and some designs (doubly linked lists, observer graphs) need
Rc<RefCell<…>>, arenas orunsafeto express at all. - Deterministic, not free, deallocation. Dropping a
Vecof a million boxed values frees a million allocations, right there, on that thread. It's a "pause" you can predict and move: a common trick is to send large values to a background thread to be dropped. Dropping a long linked list naively can even overflow the stack, because each node's drop calls the next. - No compaction. Memory comes from
malloc(or jemalloc or mimalloc). Long-running services can still fragment, and nothing ever moves objects to fix it. - No bump-pointer nursery. A GC'd language allocates short-lived objects with a pointer bump and frees them in bulk. Rust's equivalent is putting values on the stack, which the ownership model encourages, or using an arena when you know a batch will die together.
The production version of this trade
Discord's 2020 write-up Why Discord is switching from Go to Rust is the clearest real example. Their "Read States" service kept a large, long-lived cache in memory. Go's collector, which also forces a cycle at least every two minutes, had to scan that whole cache each time, which produced regular latency spikes even though the service generated very little garbage. Tuning didn't make them go away. The Rust rewrite had no collector to scan anything: the cache stayed in memory, and memory was freed exactly when entries were evicted. The spikes disappeared and average latency improved as well.
The lesson isn't "Rust beats GC." It's the cost model from the start of this post: a tracing collector's work is proportional to the live heap, so a service whose job is to hold a huge live heap is the worst case for tracing GC. Ownership's cost is proportional to the work your code does, not to how much it holds.
⚖️ The Trade-off Triangle
Every collector design is a position between three goals:
T h r o u g h p u t
( % C P U l e f t f o r y o u r c o d e )
▲
╱ ╲
╱ ╲
╱ ╲
╱ ╲
L a t e n c y ╱ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╲ F o o t p r i n t
( p a u s e t i m e s ) ( m e m o r y o v e r h e a d )
You get to optimise two. Parallel GC: throughput and footprint, with long pauses. ZGC: latency,
paying with CPU for barriers and with headroom. Go with GOGC=100: low latency and simplicity,
paying with up to 2× the live heap in memory. Rust gets all three runtime corners by adding a
fourth cost that isn't on the triangle: the programmer and the compiler do the work instead.
Underneath that is a simple equation. Say the live heap is L and the heap is allowed to grow to H. Each tracing cycle does work proportional to L, and frees H − L bytes for new allocation. So the GC cost per byte you allocate is roughly:
G C w o r k p e r a l l o c a t e d b y t e ∝ L / ( H − L )
Double the headroom, halve the GC cost. That's the whole logic behind GOGC, behind
-Xmx tuning, and behind the observation that most "GC is slow" problems are really
"heap is too close to live size" problems. Garbage collection trades memory for CPU, and
the exchange rate is set by how much spare memory you give it.
🕳️ The Bugs That Live in a Garbage-Collected Heap
Leaks by reachability. Unbounded caches, event listeners that are never removed, a closure
that captures a large object to use one field, a global Map keyed by request ID. Each is
correct from the collector's point of view: the object is reachable. Use a bounded cache, a
WeakMap/WeakRef, or remove the reference. In Node, take two heap snapshots a few minutes
apart and compare retained sizes; the leak is whatever keeps growing, and the retainer path
tells you who's holding it.
Death by allocation rate. A service with a small live heap can still spend 30% of its CPU
in GC if it allocates gigabytes per second. Every collection is cheap, but there are thousands
of them. The fix is allocating less in the hot path (reuse buffers, avoid intermediate arrays,
sync.Pool in Go), not tuning the collector.
The memory sawtooth that isn't a leak. Heap usage climbing steadily and then dropping sharply is just a GC cycle. A leak is when the bottom of each tooth (the live heap after a collection) keeps rising.
Containers and heap limits. A runtime that doesn't know about the cgroup limit sizes its
heap for the host, grows past the container's memory, and gets OOM-killed without ever running
a full GC. Modern JVMs are container-aware (-XX:MaxRAMPercentage), Go needs GOMEMLIMIT, and
Node's default old-space size doesn't always match the container. Set it explicitly with
--max-old-space-size.
Finalizers. Running user code when an object dies sounds useful and is a trap: there's no
guarantee when (or if) it runs, it can resurrect the object, and it delays reclamation by at
least a cycle. Java deprecated finalization for removal (JEP 421). Use explicit close(),
defer, with, or try-with-resources for anything that holds an external resource, and
keep FinalizationRegistry/Cleaner as a safety net, not the mechanism.
GC doesn't manage file descriptors. A socket object being collected eventually might close
its fd, but "eventually" can be after you've hit EMFILE. The collector reacts to memory
pressure, not fd pressure. External resources need deterministic cleanup.
📚 Key Takeaways
- GC frees unreachable memory, not unused memory. Liveness is reachability from roots, and every GC-language leak is a reference you forgot about.
- Tracing vs RC is a cost model choice. RC pays per pointer write and can't handle cycles alone; tracing pays per live object and in batches.
- Copying collection costs only what survives, which, combined with the generational hypothesis, is why minor GCs are cheap and why most runtimes are generational.
- Barriers are how GC reaches into your hot path. Write barriers keep remembered sets and concurrent marking correct; load barriers make concurrent compaction possible.
- Concurrent marking is correct only if one of the two lost-object conditions is broken: Dijkstra's insertion barrier, Yuasa's SATB deletion barrier, or Go's hybrid of both.
- Every runtime picks a different corner of the triangle. V8 is generational and compacting, Go is non-moving and leans on escape analysis, the JVM gives you a menu, and CPython counts references.
- GC trades memory for CPU. Cost per allocated byte is about
L / (H − L); more headroom means less collection work. - Rust decides liveness at compile time. Ownership frees values at the end of their scope,
borrowing makes use-after-free a compile error, and
Rc/Arcare opt-in reference counting for the values that really are shared. No pauses, but you pay in design effort, and cycles still needWeak.
✨ Final Thoughts
"The runtime frees memory you aren't using any more" was the sentence I'd been carrying around. The real version is less tidy and much more interesting: the runtime is continuously deciding which bytes are still reachable, while your threads rewrite the graph underneath it, and every pointer store you write pays a small tax so it can do that without stopping you.
What changed for me is how I read GC problems now. A latency spike, a sawtooth graph, an OOM in a container, a Node process that won't stop growing: each maps to a specific part of the machinery (pause, cycle, heap sizing, reachability). The collector stops being a black box that sometimes misbehaves, and becomes a system with known trade-offs that I've chosen, usually without noticing, every time I picked a language.