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