I am trying to allocate memory in JavaScript to study memory leak/consumption using the code snippet below. However
performance.memory.usedJSHeapSize
always shows the same number, 10000000 in my case. How come that number never changes despite dynamically creation of elements and attaching to DOM ?
I need a JavaScript snippet to create memory leak and monitor the usage using performance.memory.usedJSHeapSize dynamically( or any other functions if exists).
I tried this code but performance.memory.usedJSHeapSize remains at 10000000:
<body>
<p id="memory" style="position: fixed; top:10px; left:10px"></p>
<script>
setInterval(() => {
document.getElementById("memory").innerHTML = performance.memory.usedJSHeapSize
}, 300);
btn = [];
let i = 0;
setInterval(() => {
for (let j = 0; j < 1000; j++) {
++i;
let k=i;
btn[k] = document.createElement("BUTTON");
document.body.appendChild(btn[k]);
btn[k].innerHTML = k;
btn[k].addEventListener("click", function () {
alert(k);
});
}
}, 5000);
</script>
</body>
I already tired the example given in 2013 in this post, but this one no longer create memory leak either.
How do I create a memory leak in JavaScript?
performance.memory.usedJSHeapSize
does not update when the page is opened directly from the local file system.
The image below shows that the exact same code copy-pasted from the question shows increasing memory usage when accessed at localhost:
Or, you can check for yourself: https://memory-leak.surge.sh/simple/ (You can also check the original code: https://memory-leak.surge.sh/ but your browser might freeze up if left open for more than a few seconds.)
How to host the HTML like I did above:
The simplest option is to use dev tools like Browsersync or Parcel. These tools will let you open files from your local file system as if they were hosted from a server with a URL like http://localhost:1234/ . (Because a temporary web server is started on your computer.)
Another option is to actually host the files on a server. There are many options to do this:
Note: results may vary based on browser/hardware. My environment:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With