Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create memory leak and monitor memory usage in JavaScript

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?

like image 456
Waterfr Villa Avatar asked May 08 '19 15:05

Waterfr Villa


Video Answer


1 Answers

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:

Proof

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:

  • surge The tool I used for the examples above
  • Glitch (This one is cool because you can edit the files online and see changes right away)
  • Github pages

Note: results may vary based on browser/hardware. My environment:

  • Chrome Version 74.0.3729.131 (Official Build) (64-bit)
  • Windows 10
like image 110
Leftium Avatar answered Nov 14 '22 22:11

Leftium