Bryan Denny
Bryan Denny

Reputation: 27596

Question about jQuery performance and DOM: why is one method faster than the other?

I was looking at some jQuery performance tips and ran across this one that caught my interest.

Check out the following page snippet:

<html>
<head>
</head>
<body>
<select id ="myList">


</select>
<div id ="myList2">


</div>
<script language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>

<script type="text/javascript">
$(document).ready(function()
{
    console.time('test');
    var myList = $('#myList');
    var myListItems = '';

    for (i = 0; i < 1000; i++) {
        myListItems += '<option>This is list item ' + i + '</option>';
    }

    myList.html(myListItems);
    console.timeEnd('test');

    console.time('test2');
    var myList = $('#myList2');
    var myListItems = '<select  >';

    for (i = 0; i < 1000; i++) {
        myListItems += '<option>This is list item ' + i + '</option>';
    }

    myListItems += '</select>';
    myList.html(myListItems);
    console.timeEnd('test2');

}
);
</script>
</body>
</html>

Why is the second test method faster than the first (by a factor of about 4)?

Upvotes: 0

Views: 226

Answers (3)

user152108
user152108

Reputation: 31

You got it right.

Adding multiple times to the DOM item is more performance expensive then adding once.

P.S. : Straight forward code is many times does not map linearly.

Upvotes: 0

Bryan Denny
Bryan Denny

Reputation: 27596

Okay, I think I might get it.

With the first option we are adding 1000 DOM objects to one DOM object.

With the second option we are adding 1 DOM object with 1000 DOM objects to one DOM object. So we are only connecting 1 DOM object to another instead of 1000?

Am I thinking correctly? It is easier to load a bag with 1000 marbles into a box than it is to add 1000 marbles into a bag?

Upvotes: 1

Spencer Ruport
Spencer Ruport

Reputation: 35117

myList.html parses (and consequently validates) the input whereas the first test does not. It just spits out the string.

Upvotes: 0

Related Questions