Circular references in Javascript / Garbage collector

邮差的信 提交于 2019-11-26 06:37:12

问题


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 about is an explicit back-/next reference within objects. For instance:

var objA = {
    prop: \"foo\",
    next: null
};

var objB = {
    prop: \"foo\",
    prev: null
};

objA.next = objB;
objB.prev = objA;

There we go. If we do a console.log( objA ) we can see that we created an infinite chain. The big question is, is this bad ? Does it create memory leaks when not explicitly cleaned?

So do we have to

objA.next = null;
objB.prev = null;

or will the garbage collectors take care of us on constellations like this?


回答1:


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.



来源:https://stackoverflow.com/questions/7347203/circular-references-in-javascript-garbage-collector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!