Browser's "memory management"

A common memory leak in JS engines

26-03-2023

0
function f() {
    var some = [];
    while(some.length < 1e6) {
        some.push(some.length);
    }
    function unused() { some; } // causes massive memory leak
    return function() {};
}
  
var a = [];
var interval = setInterval(function() {
    var len = a.push(f());
    document.getElementById('count').innerHTML = len + ' / 500';
    if(len >= 500) {
        clearInterval(interval);
    }
}, 10);

This code demonstrates a classic closure-based memory leak where the unused inner function maintains a reference to a large array, preventing garbage collection. The function f() creates an array with 1 million numbers, the inner function unused() creates a closure that holds reference.

These kind of leaks are particularly insidious they are not obvious from looking at the retuned function. Older versions of Chromium and WebKit used to crash while executing this.