cloneNode vs createElement vs innerHTML

JavaScript performance comparison

Revision 37 of this test case created by

Preparation code

<div id="target"></div>

<script>
  var div = document.createElement('div');
  div.innerHTML = '<header class="header">Header</header><article class="article"><p>Paragraph 1</p><p>Paragraph 2</p><p>Paragraph 3</p><p>Paragraph 4</p><p>Paragraph 5</p><ul class="list"><li>Item 1</li><li>Item 2</li><li>Item 3</li><li>Item 4</li><li>Item 5</li></ul></article><footer class="footer">Footer</footer>';

function cloneNodeRecursive(node) {
  var clonedNode = node.cloneNode();

  for (var child = node.firstChild; child !== null; child = child.nextSibling) {
    clonedNode.appendChild(cloneNodeRecursive(child));
  }
   
  return clonedNode;
}

var nodeStack = [];

function cloneNodeIterative(rootNode) {
  var rootNodeClone = rootNode.cloneNode();
  
  nodeStack.length = 0;
  nodeStack.push(rootNodeClone, rootNode);

  while (nodeStack.length > 0) {
    var node = nodeStack.pop();
    var nodeClone = nodeStack.pop();

    for (var child = node.firstChild; child !== null; child = child.nextSibling) {
      var childClone = child.cloneNode();
      nodeClone.appendChild(childClone);
      nodeStack.push(childClone, child);
    }
  }

  return rootNodeClone;
}
</script>
      
<script>
Benchmark.prototype.teardown = function() {
  target.innerHTML = '';

};
</script>

Preparation code output

<div id="target"></div>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
cloneNode()
var newDiv = div.cloneNode(true);
target.appendChild(newDiv);
pending…
custom recursive cloneNode()
var newDiv = cloneNodeRecursive(div);
target.appendChild(newDiv);
pending…
custom iterative cloneNode
var newDiv = cloneNodeRecursive(div);
target.appendChild(newDiv);
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.

0 Comments