The issue of memory management became interesting, as far as I understood correctly, the garbage collector cleans up as soon as there are no more references to the object from the root

Faced a slightly non-obvious behavior, if you delete the parent container, the memory for the children continues to be allocated, even after calling the garbage collector (timeline)

We create many spans, put them on the page and cache the elements in the array, quite often I do this, because it is convenient to access them later, then I need to delete the whole thing, if I delete the elements one by one, then we give any other value to the stored file, then the memory is freed, but if you remove the container, the memory is not cleared

<!DOCTYPE html> <html> <head> <title>Test memory</title> </head> <body> <button id="start">start</button> <button id="destroyC">destroy children</button> <button id="destroyP">destroy parent</button> <div id="container"></div> <script type="text/javascript"> var _elements = []; var _container = document.getElementById('container'), _btnStart = document.getElementById('start'), _btnParentDestoy = document.getElementById('destroyC'), _btnChildDestroy = document.getElementById('destroyP'); function _start() { var element, count = 50000; for (var i = 0; i < count; i++) { element = document.createElement('span') element.innerHTML = 'Span' _elements.push(element) _container.appendChild(element) } } function _destroyParent() { _container.remove() _elements.forEach(function(item, ind, arr) { arr[ind] = null; }) console.log(_elements) _elements = null; } function _destroyChild() { _elements.forEach(function(item, ind, arr) { item.remove(); }) _elements = null; } _btnStart.addEventListener('click', _start) _btnParentDestoy.addEventListener('click', _destroyChild) _btnChildDestroy.addEventListener('click', _destroyParent) </script> </body> </html> 

  • clean console.log - Grundy
  • Removed, memory still flows, the detached DOM tree / 100001 remains in the profiler. Entries - Artem S.

0