appendChild vs. DocumentFragment vs. innerHTML

JavaScript performance comparison

Revision 20 of this test case created by Anirudh

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 = [
   text(document.createElement('b'), 'Links:'), document.createTextNode(' '), text(document.createElement('a'), 'Link A'), document.createTextNode(' | '), text(document.createElement('a'), 'Link B'), document.createTextNode(' | '), text(document.createElement('a'), 'Link C'), document.createElement('hr')];
</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
o.innerHTML = '';
for (var i = 0, imax = aElms.length; i < imax; i++) {
 o.appendChild(aElms[i].cloneNode(true));
}

var x = window.getComputedStyle(o);
pending…
DocumentFragment
oFrag = document.createDocumentFragment();
for (var i = 0, imax = aElms.length; i < imax; i++) {
 oFrag.appendChild(aElms[i]);
}

o.innerHTML = '';
o.appendChild(oFrag.cloneNode(true));

var x = window.getComputedStyle(o);
pending…
innerHTML
o.innerHTML = '<b>Links:</b> <a>Link A</a> | <a>Link B</a> | <a>Link C</a><hr>';

var x = window.getComputedStyle(o);
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