Reputation: 1317
In the code snippet below I am not adding anything new to DOM, neither do I create any dynamic data type. I also do not increase array size or anything. Yet when you run the code ( must be hosted or local hosted) in Chrome, the value of
performance.memory.usedJSHeapSize
keeps on increasing. Why?
<html>
<body>
<p id="memory" style="position: fixed; top:10px; left:10px; font-size: 1.5em;"></p>
<script>
setInterval(() => {
document.getElementById("memory").innerHTML = performance.memory.usedJSHeapSize;
}, 300);
</script>
</body>
</html>
It is also hosted for you to see (open in Chrome or Opera ):
http://appsdepo.com/temp/memory_leak.html
Upvotes: 4
Views: 3142
Reputation: 40511
There are at least two allocations in that code:
(1) performance.memory
creates a new object every time you call it. It's implemented in native code, but the JavaScript equivalent would be roughly:
Object.defineProperty(performance.__proto__, "memory",
{get: function() {
return {usedJSHeapSize: ...,
totalJSHeapSize: ...,
...: ...};
});
(2) usedJSHeapSize
returns a Number, but you're assigning that value to a setter that requires a String, so it is implicitly converted to a String, which is another allocation.
Note that neither of this is a leak: when garbage collection is triggered, all the old temporary objects that are no longer required are cleaned up. It just takes a while until enough garbage is around that Chrome decides that doing some GC is a good use of your CPU.
Upvotes: 4