Consider the following code that inserts 100,000 spans with the content '0' inside.
<body>
<script type="module">
const container = document.getElementById('root')
const CHILDREN_COUNT = 100000;
for (let i = 0; i < CHILDREN_COUNT; i++) {
const newChild = document.createElement("span");
newChild.innerHTML = '0'
container.appendChild(newChild)
}
</script>
<div id="root" style="overflow-wrap: break-word">
</div>
</body>
In my mind, after each loop, the garbage collection should clean up newChild
as there are no further references to this var. The container
itself I assume is a pointer to the DOM element, instead of being the entire thing in memory, and either way, should be cleaned after the loop executes.
However, testing reveals this page will take up 200,000kb~ of memory (per task manager in Chromium), but if CHILDREN_COUNT
is reduced to 10, it takes up only c. 30,000kb~ of memory. Could the difference be entirely down to the DOM having to hold more span
elements? Since the content for each span is minimal, I would have assumed not.
Is there something that I could do here to better manage memory use?
check DocumentFragment -> https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment
var list = document.querySelector('#list')
const CHILDREN_COUNT = 100000;
var fragment = new DocumentFragment();
for (let i = 0; i < CHILDREN_COUNT; i++) {
var spanEl = document.createElement('span');
spanEl.innerHTML ='0';
fragment.appendChild(spanEl);
}
list.appendChild(fragment);