appendChild vs. DocumentFragment vs. innerHTML

JavaScript performance comparison

Revision 5 of this test case created by Dominik Porada

Info

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

Preparation code

<div id="test1"></div>
<div id="test2"></div>
<div id="test3"></div>
<script>
  // You can read this:
  // http://ejohn.org/blog/dom-documentfragments/
 
  function text(node, txt) {
   node.appendChild(document.createTextNode(txt));
   return node;
  }
 
  function cleanUp(node) {
   node.innerHTML = "";
  }
 
  var content = [ // I hate the way jsPerf formats arrays
  document.createElement("hr"), 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")];
</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");

for (var i = 0, j = content.length; i < j; i++) {
 div1.appendChild(content[i].cloneNode(true));
}

cleanUp(div1);
pending…
DocumentFragment
var div2 = document.getElementById("test2"),
    fragment = document.createDocumentFragment();

for (var i = 0, j = content.length; i < j; i++) {
 fragment.appendChild(content[i]);
}

div2.appendChild(fragment.cloneNode(true));

cleanUp(div2);
pending…
innerHTML
var div3 = document.getElementById("test3");

div3.innerHTML += "<hr><b>Links:</b> <a>Link A</a> | <a>Link B</a> | <a>Link C</a>";

cleanUp(div3);
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