Introduction
I‘ve been programming for almost 10 years and during this time, I’ve heard about avoiding the DOM manipulation because it generates too much overhead. But I guess, I’ve never imagined how bad it could be.
I was dealing with an old bug, some processing of images done at the client side. The memory jump to more than 1 gigabyte before I was able to process 20 items and my computer crashed. I was giving myself a last chance to find where the memory leak was or think about another strategy.
Using the Code
In fact, there was no memory leak. Surprisingly, the memory increased because of the following DOM manipulation:
$("#dialog-modal p").append('<p>'+ msg +'</p>');
The bug was that the :last
selector was missing and I was appending a 1,2,3,4,5,…n times <p>
each time the line was called.
The correct expression should be:
$("#dialog-modal p:last").append('<p>'+ msg +'</p>');
Each manipulation with append
was triggering a reflow.
As Google developer site explains: “Reflow is the name of the web browser process for re-calculating the positions and geometries of elements in the document, for the purpose of re-rendering part or all of the document.”.
You can read more about DOM reflow here.
As it‘s generally suggested, when it’s possible, use show /hide to modify the DOM and avoid reflows.
Do not underestimate the overhead of reflows so when your memory sky rockets, check the code manipulating the DOM.