appendChild vs. DocumentFragment vs. innerHTML

JavaScript performance comparison

Revision 47 of this test case created

Info

Different ways to dynamically insert new elements into the DOM tree. v44: Outer loop only 200, not 2000.

Preparation code

<div id="test1">
</div>
<script>
function precompileTemplate()
{
  var docFrag=document.createDocumentFragment();
  var tmplRow = document.createElement('div');
  for (var j = 0; j < 20; j++)
  {
    var cell=document.createElement('span');
    tmplRow.appendChild(cell);
  }
  for (var i = 0; i < 200; i++)
    docFrag.appendChild(tmplRow.cloneNode(true));
  return(docFrag);
}
var compiledTemplate1 = precompileTemplate();
</script>
<script>
Benchmark.prototype.setup = function() {
    var div1 = document.getElementById("test1");
    var counter=0;
    var row, cell;
   
};

Benchmark.prototype.teardown = function() {
    div1.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; i < 200; i++)
{
  row=document.createElement('div');
  for (var j = 0; j < 20; j++)
  {
    cell=document.createElement('span');
    cell.textContent = 'test '+(counter++);
    row.appendChild(cell);
  }
  div1.appendChild(row);
}
pending…
DocumentFragment
var 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');
    cell.textContent = 'test '+(counter++);
    row.appendChild(cell);
  }
  docFrag.appendChild(row);
}
div1.appendChild(docFrag);
pending…
innerHTML
var html='';
for (var i = 0; i < 200; i++)
{
  row='<div>';
  for (var j = 0; j < 20; j++)
    row+='<span>test '+(counter++)+'</span>';
  html+=row+'</div>';
}
div1.innerHTML=html;
pending…
Template-like 0
var docFrag=document.createDocumentFragment();
var tmplRow = document.createElement('div');
for (var j = 0; j < 20; j++)
{
  cell=document.createElement('span');
  //cell.textContent = 'test';
  tmplRow.appendChild(cell);
}

for (var i = 0; i < 200; i++)
  docFrag.appendChild(tmplRow.cloneNode(true));

var spans = docFrag.querySelectorAll('span');
for(var j=0,count=spans.length;j < count;j++)
  spans[j].textContent =  'text '+(counter++);
div1.appendChild(docFrag);
pending…
Template-like 1
var docFrag=compiledTemplate1.cloneNode(true);

var spans = docFrag.querySelectorAll('span');
for(var j=0,count=spans.length;j < count;j++)
  spans[j].textContent =  'text '+(counter++);
div1.appendChild(docFrag);
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