There is the following code, which should create 16 million elements (in this case, only 4k, you need to replace 16 * 16 * 16 with 16 * 16 * 16 * 16 * 16 * 16). And after 5 million somewhere chrome eats all the RAM and that's it. Where is the leak? What to do?

const body = document.querySelector('body'); for (let i = 0, l = 16*16*16; i < l; i++) { const el = document.createElement('div'); el.style.backgroundColor = '#' + addZero(6, i.toString(16)); body.appendChild(el); } function addZero(digits_length, source){ while(source.length < digits_length) source = '0' + source; return source; } 
 body { display: flex; flex-wrap: wrap; margin: 0; padding: 0; } div { width: 1px; height: 1px; } 

  • Are you imitating such perversions with canvas? o_O - andreymal
  • @andreymal like that. - Nazar Kalytiuk

1 answer 1

I think this is not a memory leak, but she just does everything. Your code without rendering is processed ~ in 8 seconds, the weight of the entire html> 700mb, on drawing such all resources run out and the browser either hangs or bangs the tab. In the example, there is one more * 16, the limit on the size of string is exceeded.

 var start = Date.now(); const body = document.querySelector('body'); const target = 16*16*16*16*16; var elms = ''; for (let i = 0, l = target; i < l; i++) { elms += '<div style="background-color:#'+addZero(6, i.toString(16))+'"></div>'; } //body.innerHTML = elms; function addZero(digits_length, source) { while (source.length < digits_length) source = '0' + source; return source; } console.log(Date.now() - start); console.log(elms.length/1024); 
 body { display: flex; flex-wrap: wrap; margin: 0; padding: 0; } div { width: 1px; height: 1px; }