为什么从dom中删除几乎所有对象都不会导致内存不足?

Gre*_*nce 5 javascript memory-leaks snapshot google-chrome-devtools

当我打开Chrome开发者工具时,打开此网页并拍摄快照,大小为2.1MB.

当我点击其中一个按钮时,所有这些按钮和它们的div都被删除了.如果我再拍一张快照,则大小为1.6MB.

因此,当使用Chrome开发人员工具并拍摄快照时,网页总会消耗一些内存,在拍摄快照和查找内存泄漏时需要考虑这些内存吗?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <script type="text/javascript">
        var onLoadFunc = function() {
            for(var x=0;x<30000;x++) {
                var button = document.createElement("input");
                button.type = "button";
                button.value = "Destroy Content";
                button.onclick = destroyFunc;
                document.getElementById('mainDiv').appendChild(button);
            }
        };

        var destroyFunc = function() {
            var el = document.getElementById( 'mainDiv' );
            el.parentNode.removeChild(el);
        };
    </script>
</head>
<body onLoad="onLoadFunc()">
  <div id="mainDiv"/>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

csc*_*can 0

您在 1.6 MB 中看到的内容包括已被销毁但仍保留在内存中的对象,因为它们尚未被垃圾收集。

对象的销毁并不能保证它何时会被垃圾收集。