innerHTML vs. cloneNode

JavaScript performance comparison

Test case created by Kevin Decker and last updated

Info

Tests various DOM construction patterns.

Preparation code

<div id="destination"></div>
<script>
  var content = '<div class="test"><span style="color: red">Wooo Text!</span></div><div>More text!</div>',
      dest = document.getElementById("destination");
 
  // For Element cloneNode test
  var womb = document.createElement("div");
  womb.innerHTML = content;
 
  // For doc fragment test
  var frag = document.createDocumentFragment(),
      clone = womb.cloneNode(true),
      len = clone.childNodes.length;
  while (len--) {
   frag.appendChild(clone.childNodes[0]);
  }
</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
innerHTML
dest.innerHTML = content;
pending…
cloneNode
dest.innerHTML = "";
var clone = womb.cloneNode(true),
    len = clone.childNodes.length;
while (len--) {
 dest.appendChild(clone.childNodes[0]);
}
pending…
DocumentFragment
dest.innerHTML = "";
dest.appendChild(frag.cloneNode(true));
pending…
DOM post insert
dest.innerHTML = "";

var child = document.createElement('div');
child.className = "test";

var subChild = document.createElement('span');
subChild.style.color = "red";
subChild.appendChild(document.createTextNode("Wooo Text!"));
child.appendChild(subChild);
dest.appendChild(child);


child = document.createElement('div');
child.appendChild(document.createTextNode("More text!"));
dest.appendChild(child);
pending…
DOM pre insert
dest.innerHTML = "";

var child = document.createElement('div');
dest.appendChild(child);
child.className = "test";

var subChild = document.createElement('span');
child.appendChild(subChild);
subChild.style.color = "red";
subChild.appendChild(document.createTextNode("Wooo Text!"));

child = document.createElement('div');
dest.appendChild(child);
child.appendChild(document.createTextNode("More text!"));
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

Add a comment