appendChild vs. DocumentFragment vs. innerHTML (v56)

Revision 56 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
appendChild
var div1 = document.getElementById("test1"),
  row, cell;

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


div1.innerHTML = '';
ready
DocumentFragment
var div1 = document.getElementById("test1"),
  row, cell, docFrag;
docFrag = document.createDocumentFragment();
for (var i = 0; i < 200; i++) {
  row = document.createElement('div');
  for (var j = 0; j < 20; j++) {
    cell = document.createElement('span');
    text(cell, Math.random());
    row.appendChild(cell);
  }
  docFrag.appendChild(row);
}
div1.appendChild(docFrag);

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

for (var i = 0; i < 200; i++) {
  row = '<div>';
  for (var j = 0; j < 20; j++) {
    row += '<span>' + Math.random() + '</span>';
  }
  html += row + '</div>';
}
div1.innerHTML = html;
div1.innerHTML = '';
ready

Revisions

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