Click here to Skip to main content
15,886,518 members
Articles / Web Development / HTML
Tip/Trick

How Expensive Can DOM Manipulation Be

Rate me:
Please Sign up or sign in to vote.
3.92/5 (6 votes)
21 Feb 2018CPOL1 min read 7.3K   3  
How expensive DOM manipulation can be

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:

JavaScript
$("#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:

JavaScript
$("#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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Canada Canada
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --