Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is memory usage not correctly updated?

Warning: this code will eventually exhaust your browser tab's memory and crash the tab.

In the following fiddle, I have set up a process that leaks a lot of memory and continuously reports how much memory is being used. I am using the performance.memory API, which only seems to be implemented on chrome. The problem is that the amounts reported never change, despite the fact that memory usage is rapidly increasing. Instead, I would expect the number on top to continually increase.

Here is the javascript code:

(function() {

var x = [];

function createSomeNodes() {
    var div,
        i = 100,
        frag = document.createDocumentFragment();
    for (;i > 0; i--) {
        div = document.createElement("div");
        div.appendChild(document.createTextNode(i + " - "+ new Date().toTimeString()));
        frag.appendChild(div);
    }
    document.getElementById("debug").appendChild(frag);
}

function clear() { document.getElementById('stats').innerHTML = ''; }

function show(stat) { 
  var div = document.getElementById('stats');
  div.appendChild(document.createTextNode(stat));
  div.appendChild(document.createElement("div"));
 }

var start = Date.now() + 2 * 1000;

function grow() {
    x.push(new Array(1000000).join('x'));
    createSomeNodes();
    setTimeout(grow,40);

if (Date.now() < start) { return; }

              (function() {
                clear();
                var pm = window.performance && window.performance.memory;
                if (!pm) {
show("no performance.memory api");
                  return;
                }
                var lim = pm.jsHeapSizeLimit, // Memory the JavaScript heap is limited to
                    // Memory allocated on the JavaScript heap (includes free space)
                    total = pm.totalJSHeapSize,
                    used = pm.usedJSHeapSize; // Memory currently being used 
                show("Crash Index (% of Heap Limit Allocated): " + Math.round(total / lim * 100));
                show("% of Allocated Memory Used: " + Math.round(used / total * 100));
              })();

}


    setTimeout(grow,1000);
})()

If I set the variable start to a higher number, I see a higher initial value for what I have called the "crash index," but after it is first shown, even this value does not increase.

like image 484
Lyn Headley Avatar asked Apr 30 '26 22:04

Lyn Headley


1 Answers

For security reasons, Google Chrome doesn't provide precise information via performance.memory by default.

So, you have to open your browser via terminal with this flag --enable-precise-memory-info, to allow Google Chrome to show precise information about your computer.

like image 137
João Mosmann Avatar answered May 03 '26 12:05

João Mosmann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!