appendChild vs. DocumentFragment vs. innerHTML

JavaScript performance comparison

Revision 52 of this test case created

Info

Comparing three different ways to dynamically insert content into the DOM.

Preparation code

<div id="test"></div>
<script>
  function text(node, txt) {
   node.appendChild(document.createTextNode(txt));
   return node;
  }
 
  var o = document.getElementById('test'),
      aElms = [];
var elm = document.createElement('a');
elm.href='http://google.com';
elm.textContent = 'hello';
  for(var i=0;i<100;i++){
aElms.push(elm.cloneNode(true));
}
</script>
<script>
Benchmark.prototype.teardown = function() {
    o.innerHTML = '';
};
</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
for (var i = 0, imax = aElms.length; i < imax; i++) {
  o.appendChild(aElms[i]);
}
pending…
DocumentFragment
oFrag = document.createDocumentFragment();
for (var i = 0, imax = aElms.length; i < imax; i++) {
  oFrag.appendChild(aElms[i]);
}
o.appendChild(oFrag);
pending…
innerHTML
var html = '';
for (var i = 0, imax = aElms.length; i < imax; i++) {
  html += aElms[i].outerHTML;
}
o.innerHTML = html;
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