Backbone.js Memory Management, Rising DOM Node Count

前端 未结 4 1319
忘了有多久
忘了有多久 2020-12-14 09:59

Situation: I\'m working on a pretty decently complex single page Backbone app that could potentially be running for 8-12+ hours straight. Because of this, t

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-14 10:59

    I assumed that once the event listeners were properly disposed of that the DOM Node Count would just manage itself, but this doesn't seem to be the case.

    If I got you right you are trying to dispose of the node by removing listeners from it, is that the case?

    Note that adding event listener to a DOM node doesn't prevent the node from being garbage collected, the dependency is in opposite direction: while the node is alive the listener function will not be collected.

    • Is there a proper way to dispose of DOM Nodes so that they will be properly garbage collected, or is this DOM Node Count a running total that will never decrease?

    To make sure a DOM node can be garbage collected you should

    1. Remove the node from the document tree.
    2. Clear all references from javascript to the node AND to all nodes in the same subtree as reference from javascript to one of the nodes in the subtree will hold whole subtree.

    So it is not enough to just remove listeners from a node to make it collectable. Moreover, it is not necessary to remove listeners from a node if you want the node to be collected.

    The DOM node count should be decreasing when some nodes are collected by GC and destroyed. The number indicates current amount of DOM nodes that have been created but not destroyed so it shouldn't grow indefinitely unless there is a memory leak.

    • Is the DOM Node Count even a reliable figure?

    Yes. It should be a reliable figure as it is incremented whenever a new DOM node is created and decremented when it is destroyed. So the implementation is quite straightforward to trust it.

提交回复
热议问题