Circular references in Javascript / Garbage collector

Any half-decent garbage collector will handle cycles.

Cycles are only a problem if you do naive reference counting.

Most garbage collectors don’t do ref-counting (both because it can’t handle cycles, and because it’s inefficient). Instead, they simply follow every reference they can find, starting from “roots” (typically globals and stack-based variables), and mark everything they can find as “reachable”.

Then they simply reclaim all other memory.

Cycles are no problem because they just mean that the same node will be reached multiple times. After the first time, the node will be marked as “reachable” already, and so the GC will know that it’s been there already, and skip the node.

Even more primitive GC’s based on reference-counting typically implement algorithms to detect and break cycles.

In short, it’s not something you have to worry about.
I seem to recall that IE6’s Javascript GC actually failed to handle cycles (I could be wrong, it’s been a while since I read it, and it’s been much, much longer since I touched IE6), but in any modern implementation, it is no problem.

The entire point in a garbage collector is to abstract away memory management. If you have to do this work yourself, your GC is broken.

See MDN for more information on modern garbage collection and the mark-and-sweep algorithms that are used.

Leave a Comment