14.3 Reference Counting vs Tracing Collection

APPROACHESSTATUS: DEVELOPINGLEVEL: INTERMEDIATEREVIEWED: 2026-11-18
Before this page Garbage Collection

14.3.1 The choice

When memory is no longer needed, it must be reclaimed. Two philosophies exist. Reference counting tracks how many pointers reference each object. When the count drops to zero, the object is freed immediately. Tracing collection walks reachable objects from roots, marks them, and frees everything else.

Each strategy has different tradeoffs for latency, throughput, and memory fragmentation.

14.3.2 Overview

This choice shapes the garbage collector’s behavior: how often it runs, how long pauses last, and how predictable memory usage becomes.

Reference counting is attractive for interactive systems, because memory comes back as references drop, without a separate collection pause. It adds overhead to every reference change. A simple tracing collector pauses the program but spreads its cost over many allocations.

14.3.3 Option A: Reference Counting

Each object holds a counter: how many pointers reference it. When a pointer is copied, the counter increments. When a pointer is deleted, the counter decrements. When the count reaches zero, the object is freed immediately.

Benefit: no tracing pauses. An object is freed the moment its last reference drops, synchronously, in the code that dropped it. Freeing a large structure can still take a long time, because every object it held is freed in turn.

Cost: every pointer assignment must update the counter, and once threads share objects, the update must be atomic. In R, binding a value to a variable or storing it in a list updates its count, so ordinary function calls update counts many times.

Example: a function f(a, b, c, d) assigns parameters to a list and calls g(). Each parameter reference increments and decrements the counter. In a tight loop, this overhead multiplies.

Cycles are a problem. If object A holds a pointer to B and B holds a pointer to A, neither count can reach zero. Both leak. Breaking cycles requires detecting and special-casing them (expensive) or using weak pointers (complex API).

14.3.4 Option B: Tracing Collection (Mark-Sweep)

The collector starts at GC roots: the global environment, the call stack, registers, thread-local state. It walks the object graph, marking reachable objects. Unmarked objects are freed.

Benefit: cycles are collected automatically. No special casing needed.

Cost: a simple tracing collector stops the world. All threads pause while it runs. Incremental and concurrent collectors, such as Go’s and the JVM’s ZGC, shorten the pause at the price of barriers on the program’s own reads or writes. On a heap with millions of live objects, a full stop-the-world mark can take milliseconds or longer.

Example: a graph with circular references (A points to B, B points to A) leaks in reference counting. Mark-sweep finds it easily. No cycle detector is needed.

Marking costs time in proportion to the live objects, and sweeping in proportion to the whole heap. A heap that is 90 percent reachable costs the most to mark and gives back the least memory. A heap that is 10 percent reachable is cheap to mark and returns most of its space.

Generational collection reduces pause times. Young objects die quickly. Collection focuses on the young generation. Old objects are scanned less frequently. This makes collection pauses more predictable.

14.3.5 Scored on the nine dimensions

Dimension Reference Counting Tracing Collection
Isolation Per-interpreter, each object tracks local references only Per-interpreter, each collector has its own roots and mark state
Data movement Counters embedded in every SEXP, updated on copy Mark bits embedded in every SEXP, updated during collection
Startup cost Identical for both Identical for both
Steady-state overhead High: counter updates on every copy and assignment Low: marks happen infrequently during collection pauses
Memory behavior Immediate reclamation, low peak memory Generational heaps reduce pause, higher peak between collections
Portability Requires atomic counter operations on shared data Requires root scanning, plus write barriers if it is generational or concurrent
Package compatibility C code must increment and decrement exactly, or it leaks or frees too early (CPython’s rule) C code must keep objects protected while it uses them (R’s PROTECT rule), and leaks only what it preserves and never releases
Failure containment Counter overflow is subtle, leaks are silent Collection pause affects all threads using this heap
Determinism Immediate reclamation is deterministic Collection pause timing depends on heap state

14.3.6 Where each one wins

Reference counting wins when latency is critical (soft real-time, interactive UI) and workloads do not have cycles (data flow graphs are acyclic).

Reference counting suits long-running interactive applications, since there is no collection pause to freeze a UI. CPython uses this strategy despite its drawbacks.

Tracing collection wins when throughput matters and pauses are acceptable (batch jobs, scientific computing) and cycles are common (doubly linked lists, graphs with back pointers).

Tracing collection is the default for managed runtimes such as the JVM, .NET and Go. Rust has no garbage collector: it frees memory through ownership, and offers reference counting (Rc, Arc) as library types.

In practice, hybrid systems are common. Python uses reference counting with a cycle detector. R is a hybrid of a different kind: it keeps a reference count in every object, but only to decide whether a value can be modified in place, and it frees memory only through its tracing collector.

14.3.7 R today

GNU R keeps a reference count in each object header, in the field that held NAMED before R 4.0.0. R uses the count only to decide whether a value can be modified in place: when nothing else refers to an object that is about to change, R changes it instead of copying it. The count saturates, and MARK_NOT_MUTABLE pins it at its maximum (src/include/Defn.h).

R frees memory only through its garbage collector, a generational mark-sweep collector that runs when an allocation finds the heap past its current threshold. It marks from GC roots that include the symbol table, the global and base environments, the context stack, the protect stack and the precious list (RunGenCollect in src/main/memory.c), and frees what it did not reach.

R has no cycle detector and needs none, because a reference count never frees anything; a cycle is just more garbage for the tracing collector. Environments and closures form cycles all the time (a function defined in an environment is stored in that environment and refers back to it). What C code can leak is an object it passed to R_PreserveObject and never released.

R’s collector has two old generations (NUM_OLD_GENERATIONS is 2 in memory.c). Most collections examine only the youngest objects, and older generations are collected less often.

14.3.8 Relevance to my work

threaded-r keeps R’s arrangement: reference counts for copy decisions, and a generational mark-sweep collector, now one per interpreter heap.

With one collector per interpreter heap, one interpreter’s collection should not pause the others. Process-wide locks that remain in the fork could still couple them, and the pause behavior has not been measured.

Can an object shared between interpreters keep a reference count at all? Every binding in any interpreter writes the count, so a shared vector would need its count frozen. R already has the mechanism, since the count saturates at its maximum, and threaded-r’s immortal constants are pinned there. Whether that is enough for shared immutable vectors is open.

r-in-rust uses a precise mark-sweep collector. Each interpreter owns its heap and runs its own collector, so no collection state is shared.

Where this appears

  • threaded-r Keeps R’s reference counts, used only for copy decisions, and R’s generational mark-sweep collector, now one per interpreter heap.
  • r-in-rust (rrs) Uses mark-sweep tracing collection. Each interpreter owns its heap and GC.

Where to go next

Back to top