Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

212
Visualizações
How to create DOM elements in JS memory-efficiently?

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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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);

enter image description here

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda