Sub topic 4
Reference Counting and Why Cycles Broke It
This chapter assumes you know JavaScript objects, functions, and closures, and that you understand reachability from the previous chapter: an object stays alive while some chain of references from a root, such as a global or a local variable on the call stack, leads to it. Here you will study an older and simpler strategy for deciding when memory can be freed. It is called reference counting. You will see why it fails on circular references, and why every modern JavaScript engine replaced it.
The idea: count the pointers
Reference counting gives every heap object a hidden integer. That integer records how many references currently point to the object. The rule is short:
- When a new reference to the object is created, increment the count.
- When a reference is overwritten, goes out of scope, or its owner is destroyed, decrement the count.
- When the count reaches zero, free the object immediately. Then decrement the count of every object it referenced.
The last step can cascade. Freeing one object can drop another object's count to zero, and that frees a third, and so on.
Here is the familiar two-variable example, annotated with the counts a reference-counting engine would keep:
let user = { name: "Ada" }; // object count: 1 (user)
let admin = user; // object count: 2 (user, admin)
user = null; // object count: 1 (admin)
admin = null; // object count: 0 -> freed right hereFor this program, reference counting and reachability give the same answer. The object becomes garbage when the last reference disappears, and a reference-counting engine frees it on that exact line. Tracing collectors make no such promise.
A working simulation
JavaScript hides its memory manager, so you cannot watch real reference counts. You can model one, though. The RcHeap class below stores objects in a Map, tracks a count for each, and records which objects each one points to. Run it in Node.js or a browser console.
class RcHeap {
constructor() {
this.objects = new Map();
this.nextId = 1;
}
alloc(name) {
const id = this.nextId++;
this.objects.set(id, { name, count: 0, refs: new Set() });
return id;
}
retain(id) {
this.objects.get(id).count++;
}
release(id) {
const obj = this.objects.get(id);
obj.count--;
if (obj.count === 0) {
this.objects.delete(id);
console.log(`freed ${obj.name}`);
for (const child of obj.refs) this.release(child); // cascade
}
}
// Store a reference from one heap object to another.
link(fromId, toId) {
this.objects.get(fromId).refs.add(toId);
this.retain(toId);
}
live() {
return [...this.objects.values()].map((o) => `${o.name}(${o.count})`);
}
}
// A tree: root -> child -> grandchild
const heap = new RcHeap();
const root = heap.alloc("root");
heap.retain(root); // a variable holds root
const child = heap.alloc("child");
const grandchild = heap.alloc("grandchild");
heap.link(root, child);
heap.link(child, grandchild);
console.log(heap.live()); // [ 'root(1)', 'child(1)', 'grandchild(1)' ]
heap.release(root); // the variable is cleared
// freed root
// freed child
// freed grandchild
console.log(heap.live()); // []Releasing the single external reference to root frees the whole tree in one cascade. Nothing scans the heap, and no collector runs later. That immediacy is the main appeal of reference counting.
The cycle problem
Now give two objects references to each other. This is the makeCycle pattern from the Topic Spine, run through the simulation:
const heap = new RcHeap();
// Inside makeCycle(): two locals, a and b
const a = heap.alloc("a");
heap.retain(a); // local variable a
const b = heap.alloc("b");
heap.retain(b); // local variable b
heap.link(a, b); // a.other = b -> b count 2
heap.link(b, a); // b.other = a -> a count 2
// makeCycle() returns: both locals go out of scope
heap.release(a); // a count 1
heap.release(b); // b count 1
console.log(heap.live()); // [ 'a(1)', 'b(1)' ]Nothing is printed as freed. Each object still has a count of 1, and the reference keeping each one alive comes from the other object. No root can reach either of them, so by the reachability rule both are garbage. Reference counting never asks about reachability, though. It only checks whether the count is zero, and inside a cycle the count can never reach zero.
Cycles are common in real programs:
- Doubly linked lists and trees with
parentpointers. - DOM nodes, where
parentNode,firstChild, andnextSiblingall point at each other. - An object that stores a callback, where the callback's closure refers back to the object.
- Any graph structure, such as a scene graph, a dependency graph, or an ORM entity linked to its relations.
A pure reference counter leaks every one of these.
The historical damage: Internet Explorer and the DOM
JavaScript developers met this problem in practice. In Internet Explorer 6 and 7, the JScript engine managed JavaScript objects with a tracing collector, but DOM nodes were COM objects managed by reference counting. If a cycle crossed that boundary, neither memory manager could see the whole cycle, so the memory was never released:
function attach() {
const element = document.getElementById("button");
element.onclick = function () {
// This closure captures `element`, so:
// DOM node -> onclick function -> closure scope -> DOM node
element.style.color = "red";
};
}
attach();The DOM node held the function. The function's closure held the node. In those browsers the memory stayed allocated after you navigated to another page, until the browser was closed. That era produced folk advice such as "always set element.onclick = null on unload." The advice is obsolete in modern engines, but you will still see it in old code.
Trade-offs of reference counting
Reference counting is still widely used outside JavaScript engines, so it helps to know what it does well and what it costs.
| Property | Reference counting | Tracing (reachability from roots) |
|---|---|---|
| When garbage is freed | Immediately, when the count hits zero | Later, when the collector runs |
| Cycles | Leak unless extra machinery is added | Collected naturally |
| Cost per pointer write | Increment and decrement on every assignment | Usually none, or a cheap write barrier |
| Pause behaviour | Spread out, but a large cascade can pause | Pauses for marking, reduced by modern techniques |
| Multi-threading | Counts need atomic operations | Coordinated by the collector |
| Memory overhead | A count field per object | Mark bits or side tables |
| Deterministic cleanup | Yes, useful for files and locks | No |
Two costs matter most. First, every assignment changes counts. Code like node = node.next in a loop becomes a decrement, an increment, and a zero check on every iteration. With threads, those operations must be atomic, which costs more. Second, cascades are unbounded. Releasing the head of a list with a million nodes frees a million objects on that one line. Deterministic, then, does not mean pause-free.
How other systems live with cycles
Languages that keep reference counting add a second mechanism to handle cycles:
- CPython uses reference counting as its main strategy and runs a separate cycle detector on container objects.
- Swift and Objective-C (ARC) have no cycle collector. The programmer breaks cycles by marking one side
weakorunowned. - Rust offers
Rc<T>andWeak<T>. A cycle made only ofRcleaks, and the language accepts that as safe behaviour. - Firefox (Gecko) runs a cycle collector for its C++ DOM objects alongside SpiderMonkey's tracing collector. This is the fix for the IE-style boundary problem.
The cycle detector idea is called trial deletion. For each object, subtract the references that come from other objects in the heap. Anything left over must come from outside the heap, which means from a root. Objects with leftover counts, and everything they reach, are alive. Everything else is cyclic garbage. Add this function to the earlier simulation:
function findCyclicGarbage(heap) {
// Start with each object's full count.
const external = new Map();
for (const [id, obj] of heap.objects) external.set(id, obj.count);
// Subtract references that come from other heap objects.
for (const obj of heap.objects.values()) {
for (const childId of obj.refs) {
external.set(childId, external.get(childId) - 1);
}
}
// Objects with leftover counts are held from outside: keep them
// and everything they reach.
const alive = new Set();
const stack = [...external].filter(([, n]) => n > 0).map(([id]) => id);
while (stack.length > 0) {
const id = stack.pop();
if (alive.has(id)) continue;
alive.add(id);
stack.push(...heap.objects.get(id).refs);
}
return [...heap.objects.keys()]
.filter((id) => !alive.has(id))
.map((id) => heap.objects.get(id).name);
}
// Using the `heap` from the cycle example above:
console.log(findCyclicGarbage(heap)); // [ 'a', 'b' ]Notice what the fix needed: a walk that starts from externally held objects and follows references. That is a tracing pass. Once you need one anyway, it is simpler to make tracing the whole strategy. JavaScript engines did exactly that, and the next chapter covers how mark-and-sweep works.
Common misconceptions
- "Setting a variable to
nullfrees the object." It removes one reference. The object becomes eligible for collection only if nothing reachable still points to it, and the engine decides when to reclaim it. - "Cycles leak in JavaScript." They do not in any modern engine. The real leaks you will meet later are reachable objects you forgot about, not unreachable cycles.
- "
delete obj.propfrees memory." It removes a property, which removes one edge in the object graph. The same reachability rule applies to the value it pointed to.
Exercise
In the RcHeap simulation, create objects p and c, give p a variable reference, link p -> c and c -> p (a parent pointer), then release p's variable reference. What does heap.live() show, and which of the two objects would a JavaScript engine collect?
Show answer
heap.live() shows [ 'p(1)', 'c(1)' ]. Releasing the variable drops p from 2 to 1, so nothing cascades, and c stays at 1 because p still points to it. A JavaScript engine would collect both, because no root reaches either object.
Exercise
A Swift developer stores a closure on an object, and the closure captures that same object. Why does this leak in Swift but not in JavaScript, and how does the Swift developer fix it?
Show answer
Swift's ARC is pure reference counting with no cycle collector, so the object-to-closure-to-object cycle keeps both counts above zero for good. JavaScript engines trace reachability from roots, so the cycle is collected once nothing outside it is reachable. In Swift, the fix is to capture the object weakly, for example with [weak self], so one edge of the cycle does not add to the count.
Exercise
Reference counting frees objects deterministically. Give one situation where that is an advantage and one where the cascade it causes is a drawback.
Show answer
It is an advantage for resources that must be released promptly, such as file handles or locks tied to an object's lifetime. It is a drawback when releasing the last reference to a large structure, such as a list with a million nodes, frees everything in one synchronous cascade and causes a noticeable pause on that line.