appendChild vs. DocumentFragment vs. innerHTML (v28)

Revision 28 of this benchmark created on


Description

Comparing 3 different ways to dynamically insert new elements into the DOM tree.

Preparation HTML

<div id="test1">
</div>
<script>
function text(node, txt) {
    node.appendChild(document.createTextNode(txt));
    return node;
  }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
innerHTML
var div1 = document.getElementById("test1"),
  row, cell, html = '',
  phrase = 'asdf';

for (var i = 0; i < 2000; i++) {
  html += '<div>';
  for (var j = 0; j < 20; j++) {
    html += '<span>' + phrase + '</span>';
  }
  html += '</div>';
}
div1.innerHTML = html;
div1.innerHTML = '';
ready
DocumentFragment
var div1 = document.getElementById("test1"),
  row, cell, docFrag,
  phrase = 'asdf';

docFrag = document.createDocumentFragment();
for (var i = 0; i < 2000; i++) {
  row = document.createElement('div');
  for (var j = 0; j < 20; j++) {
    cell = document.createElement('span');
    text(cell, phrase);
    row.appendChild(cell);
  }
  docFrag.appendChild(row);
}
div1.appendChild(docFrag);

div1.innerHTML = '';
ready
appendChild
var div1 = document.getElementById("test1"),
  row, cell,
  phrase = 'asdf';

for (var i = 0; i < 2000; i++) {
  row = document.createElement('div');
  for (var j = 0; j < 20; j++) {
    cell = document.createElement('span');
    text(cell, phrase);
    row.appendChild(cell);
  }
  div1.appendChild(row);
}


div1.innerHTML = '';
 
ready

Revisions

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