Sub topic 4
Reference Counting and Why Cycles Broke It
This chapter assumes you know JavaScript objects and functions and have read the previous chapter on reachability and garbage collection roots. Reference counting is an older strategy for deciding when memory can be freed. Modern JavaScript engines no longer use it for the JavaScript heap. It is still worth learning because its main weakness, circular references, explains why engines moved to mark-and-sweep.
The working model
Reference counting is a garbage collection strategy where every object keeps a count of how many references point to it. The engine updates that count as the program runs:
- The count goes up by one when a reference to the object is stored in a variable, property, or array slot.
- The count goes down by one when that reference is overwritten, deleted, or goes out of scope.
- When the count reaches zero, the object is freed right away. Any references it held are released too, which can bring other counts to zero.
Here is a simple case with the counts written in the comments:
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 immediatelyThe approach has real strengths. Memory is reclaimed as soon as it becomes garbage, so the program never has to stop for a large collection pass. The work is spread across ordinary assignments. For this reason, systems such as CPython, Swift's ARC, and COM still use reference counting.
The cycle problem
Reference counting only looks at how many references point to an object. It never asks whether a root can reach that object. That difference breaks down when objects reference each other:
function makeCycle() {
const a = {}; // a's object count: 1 (local a)
const b = {}; // b's object count: 1 (local b)
a.other = b; // b's object count: 2
b.other = a; // a's object count: 2
}
makeCycle();
// The locals a and b go out of scope: each count drops to 1.
// Each object is still referenced by the other, so neither count reaches 0.When the function returns, nothing reachable points to either object. Their counts stay at 1 anyway, because each object holds the other's only remaining reference. A pure reference counter never frees them, and that memory leaks for the rest of the program's life.
Cycles are common in real code. Parent and child nodes in a tree, doubly linked lists, and an object that registers itself as a callback on another object all create them.
The historical leak: IE and the DOM
The JavaScript engines in Internet Explorer 6 and 7 used a tracing collector. DOM objects, however, were COM objects managed by reference counting. A cycle that crossed between the two worlds could not be collected by either system:
function attach() {
const el = document.getElementById("button");
el.onclick = function () {
// This closure captures el, so the closure references el...
console.log(el.id);
};
// ...and el references the closure through onclick. That makes a cycle.
}In those browsers, this pattern leaked the element and the closure until the page was unloaded, and sometimes until the browser was closed. Developers worked around it by setting el.onclick = null on unload. Modern browsers trace through both JavaScript and DOM objects, so this pattern no longer leaks.
Common misconceptions
| Belief | Reality |
|---|---|
| "Setting a variable to `null` frees the object." | It only removes one reference. The object is freed once nothing reachable points to it. |
| "Circular references leak in JavaScript." | They leaked under reference counting, as in old IE's DOM. They do not leak in modern engines. |
| "Reference counting is obsolete everywhere." | It is still used in CPython, Swift, and COM, usually with extra cycle detection added. |
The next chapter covers mark-and-sweep, the algorithm that replaced reference counting for the JavaScript heap.
Exercise
Under pure reference counting, what is each object's count after this code runs, and is either object freed? let p = { }; let c = { parent: p }; p.child = c; p = null; c = null;
Show answer
Both counts end at 1 because p.child references c and c.parent references p. Neither object is freed under reference counting, even though no root can reach them. A mark-and-sweep collector would free both.
Exercise
Why does reference counting free memory sooner than a tracing collector for objects that are not part of a cycle?
Show answer
It frees an object the moment its count reaches zero, during the assignment that removed the last reference. A tracing collector waits until its next collection cycle to find unreachable objects.