appendChild vs. DocumentFragment vs. innerHTML (v20)

Revision 20 of this benchmark created by Anirudh on


Description

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

Preparation HTML

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

Test runner

Ready to run.

Testing in
TestOps/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);
ready
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);
ready
innerHTML
o.innerHTML = '<b>Links:</b> <a>Link A</a> | <a>Link B</a> | <a>Link C</a><hr>';

var x = window.getComputedStyle(o);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.