Comapre of DOM generation methods

JavaScript performance comparison

Test case created by Fesor

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<style>.content {display:none;}</style>
<div class="content"></div>
<script>
Benchmark.prototype.setup = function() {
    var list = ["Germany", "USA", "Denmark", "Norway", "Sweden", "Russia"];
};

Benchmark.prototype.teardown = function() {
    $('.content').empty();
};
</script>

Preparation code output

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Only jQuery
var myselect = $('<select/>', { id: 'myselect'});
//Наполняем список
$.each(list, function() {
    $('<option/>', {
        val:  this,
        text: this
    }).appendTo(myselect);
});
myselect.val('Norway');
$('.content').append(myselect);
pending…
jQuery with native loops
var myselect = $('<select/>', { id: 'myselect'});
//Наполняем список
for(var i=0;i<list.length;i++) {
    $('<option/>', {
        val:  list[i],
        text: list[i]
    }).appendTo(myselect);
}
myselect.val('Norway');
$('.content').append(myselect);
 
pending…
jQuery with string concatenation
var myselect = '<select id="myselect">';
//Наполняем список
for(var i=0;i<list.length;i++) {
    myselect += '<option value="' + list[i] + '"';
    if (list[i] === 'Norway') {
        myselect += ' selected';
    }
    myselect += '>'+list[i]+'</option>';
}
myselect += '</select>';
$('.content').append(myselect);
pending…
Native DOM building
var myselect = document.createElement("select");
    myselect.setAttribute("id", "myselect");

//Наполняем список
for(var i=0;i<list.length;i++) {
    var option = document.createElement("option");
    option.setAttribute("value", list[i]);
    if (list[i] === 'Norway') {
        option.setAttribute("selected", "selected");
    }
     option.innerHTML = list[i];
     myselect.appendChild(option);
}
$('.content').append(myselect);
pending…
Native DOM building using documentFragment and native selectors
// создаем временное вместилище
var fragment = document.createDocumentFragment();
// сам список
var myselect = document.createElement("select");
    myselect.setAttribute("id", "myselect");

//Наполняем фрагмент
for(var i=0;i<list.length;i++) {
    var option = document.createElement("option");
    option.setAttribute("value", list[i]);
    if (list[i] === 'Norway') {
        option.setAttribute("selected", "selected");
    }
     option.innerHTML = list[i];
     fragment.appendChild(option);
}
myselect.appendChild(fragment);
document.getElementsByClassName('content')[0].appendChild(myselect);
 
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment