Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does removing almost all objects from dom not result in lower memory?

When I open Chrome developer tools, open this web page, and take a snapshot, the size is 2.1MB.

When I click on one of the buttons, all of them and their div are removed. If I then take another snapshot, the size is 1.6MB.

So is it the case that when using Chrome developer tools and taking snapshots, there will always be some memory consumed by the web page, that you need to account for when taking snapshots and looking for memory leaks?

<!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>
like image 873
Greg Lafrance Avatar asked Nov 11 '22 15:11

Greg Lafrance


1 Answers

You see in the snapshot everything that javascript engine keeps in the heap. The javascript engine (v8) actually uses heap for almost everything include the generated code for your page, internal v8 scripts, objects, maps etc.

It may confuse you because you can't control the lifetime of these objects but it would be bigger problem if we hide that internal things in the snapshot. In that case you would ask why this object still alive when all the references to it from my objects were removed. Or why the empty page uses 1.6mb of js heap and heap snapshot shows nothing. etc.

like image 63
loislo Avatar answered Nov 14 '22 21:11

loislo