Circular references in Javascript / Garbage collector

前端 未结 1 1090
不知归路
不知归路 2020-11-27 04:59

Can somebody explain in detail how Javascript engines deal with circular references ? Is there a big difference between browsers or even node.js ?

What I\'m talking

相关标签:
1条回答
  • 2020-11-27 05:05

    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.

    0 讨论(0)
提交回复
热议问题