DOM vs innerHTML

JavaScript performance comparison

Revision 18 of this test case created by matt g.

Preparation code

<div id='sample'>
  <h1 id='title'>Title</h1>
  <h2 id='subtitle'>by</h2>
  <div id='content'>
  </div>
</div>
<script>
Benchmark.prototype.setup = function() {
    var colors = ["red", "yellow", "green", "cyan", "blue", "magenta"];
};

Benchmark.prototype.teardown = function() {
    var sample = document.getElementById('sample');
    sample.innerHTML = "<h1 id='title'>Title</h1><h2 id='subtitle'>by</h2><div id='content'></div>";
};
</script>

Preparation code output

Title

by

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
DOM
var title = document.getElementById('title');
var subtitle = document.getElementById('subtitle');
var content = document.getElementById('content');

title.firstChild.nodeValue = "Colors";
subtitle.firstChild.nodeValue += " John Doe";

var list = document.createElement('ul');
for (var i = 0, l = colors.length; i < l; ++i) {
  var item = document.createElement('li');
  item.className = "item";
  item.appendChild(document.createTextNode(colors[i]));
  list.appendChild(item);
}

content.appendChild(list);
pending…
innerHTML
var title = document.getElementById('title');
title.innerHTML = "Colors";

var subtitle = document.getElementById('subtitle');
subtitle.innerHTML += " John Doe";

var list = "<ul>";
for (var i = 0, l = colors.length; i < l; ++i) {
  list += "<li class='item'>" + colors[i] + "</li>";
}
list += "</ul>";

var content = document.getElementById('content');
content.innerHTML = list;
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