appendChild vs. DocumentFragment vs. innerHTML

JavaScript performance comparison

Revision 43 of this test case created

Info

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

Preparation code

<div id="test1">
</div>
<script>
function text(node, txt) {
    node.appendChild(document.createTextNode(txt));
    return node;
  }
</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
var div1 = document.getElementById("test1"), row, cell;

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


div1.innerHTML='';
pending…
DocumentFragment
var div1 = document.getElementById("test1"), row, cell, docFrag;
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, 'test');
       row.appendChild(cell);
   }
   docFrag.appendChild(row);
}
div1.appendChild(docFrag);

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

for (var i = 0; i < 2000; i++) {
   row='<div>';
   for (var j = 0; j < 20; j++) {
       row+='<span>test</span>';
   }
   html+=row+'</div>';
}
div1.innerHTML=html;
div1.innerHTML='';
pending…
DocumentFragment 2
var div1 = document.getElementById("test1"), row, cell, docFrag;
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');
       cell.appendChild(document.createTextNode('test'))
       row.appendChild(cell);
   }
   docFrag.appendChild(row);
}
div1.appendChild(docFrag);

div1.innerHTML='';
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