appendChild vs. DocumentFragment vs. innerHTML

JavaScript performance comparison

Revision 9 of this test case created by chris bodar

Info

Comparing 4 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>
<div id="test4"></div>
<script>
  // You can read this: <http://ejohn.org/blog/dom-documentfragments/>
 
  function text(node, txt) {
    node.appendChild(document.createTextNode(txt));
    node.setAttribute('class', 'hello-world');
    return node;
  }
 
  function cleanUp(node) {
    node.innerHTML = "";
  }
 
  var content = [
    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 class="hello-world">Links:</b> <a class="hello-world">Link A</a> | <a class="hello-world">Link B</a> | <a class="hello-world">Link C</a>';

cleanUp(div3);
pending…
“Offline” node method
var div4 = document.getElementById("test4"),
    container = document.createElement("div");

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

div4.appendChild(container);

cleanUp(div4);
pending…
insertAdjacentHTML (not all browsers)
var div3 = document.getElementById("test3");
  div3.insertAdjacentHTML("BeforeEnd",'<hr><b class="hello-world">Links:</b> <a class="hello-world">Link A</a> | <a class="hello-world">Link B</a> | <a class="hello-world">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:

1 comment

chris bodar (revision owner) commented :

Going to remove the loops next as they are not a fair comparison - node should be prebuilt to compare to string

Add a comment