Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

208
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda