appendChild vs. DocumentFragment vs. innerHTML

JavaScript performance comparison

Revision 19 of this test case created by Chris Khoo

Info

NOTE: This test is a work in progress & wrong at the moment!

Preparation code

<ul id="test">
  <li></li>
  <li></li>
  <li></li>
</ul>
<script>
Benchmark.prototype.setup = function() {
    var testElt = document.getElementById('test');
    var fragment = testElt.cloneNode(true);
};
</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
appendChild
testElt.innerHTML = '';
for (var i = 0; i < 2; i++) {
    var li = document.createElement('li');
    li.innerText = Math.random();
    testElt.appendChild(li);
}
pending…
DocumentFragment
testElt.innerHTML = '';
for (var i = 0; i < 2; i++) {
    var li = fragment.childNodes[i];
    li.innerText = Math.random();
}
testElt.appendChild(fragment);
pending…
innerHTML
testElt.innerHTML = '';
var string = '';
for (var i = 0; i < 2; i++) {
    string += '<li>' + Math.random() + '</li>';
}
testElt.innerHTML = string;
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