Optimizing DOM manipulations

Often there arises a need to make changes to DOM structure, be it adding, removing or relocating elements. And there are so many ways to do them! So today I was just curious to know how fast is one approach than the other. I’ll use two ways and try to show you how long they took to run! And believe me you’ll be amazed!

  1. Live addition to DOM structure using jQuery’s appendTo()
    for(var i=0; i<10000; i++) {
      //assuming an ol element with id = ol1 is present in our DOM
      $('<li>I am an ordinary list element.</li>').appendTo('#ol1');
    }
    
  2. Adding in one go using jQuery’s .html()
    var domString = "";
    for(var i=0; i<10000; i++) {
      //creating a string of html
      domString += '<li>I am an ordinary list element.</li>';
    }
    //adding it in one go
    $('#ol2').html(domString);
    

The Verdict

First approach of adding elements to live DOM tree took ~1296 milliseconds and the second approach to concatenate a string of elements and then add it in one go took just 41 milliseconds.

So the second approach is 30 times faster than the first approach which does additions to a live DOM!

You can check the code on jsfiddle
http://jsfiddle.net/ankeetmaini/fpTXJ/2/

And you can check this live sample, which demonstrates both the approaches and gives the milliseconds elapsed in each approach! This is cool!
http://jsfiddle.net/ankeetmaini/fpTXJ/2/embedded/result/

Advertisements

One thought on “Optimizing DOM manipulations”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s