views:

98

answers:

3

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)?

A: 

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

Spencer Ruport
+1  A: 

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?

Bryan Denny
Correct, its much faster to add 1 DOM object with alot of children then it is to add each one of its children one by one.
PetersenDidIt
A: 

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.