innerHTML vs createElement test

JavaScript performance comparison

Revision 8 of this test case created by Ben

Preparation code

</script>
<div id="container">
</div>
<script>
Benchmark.prototype.setup = function() {
    document.getElementById('container').innerHTML = '';
};

Benchmark.prototype.teardown = function() {
    document.getElementById('container').innerHTML = '';
};
</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
1000 element string innerHTML
var innerHTMLstr = '<div>';
var i;
for (i = 0; i < 1000; i++) {
  innerHTMLstr += '<div><span>' + i + '</span></div>';
}
innerHTMLstr+='</div>';

document.getElementById('container').innerHTML = innerHTMLstr;
pending…
1000 element innerHTML
var container = document.getElementById('container');
var outerdiv = document.createDocumentFragment();
var i, div, span;
for (i = 0; i < 1000; i++) {
  div = document.createElement('div');
  span = document.createElement('span');
  span.innerHTML = i;
  div.appendChild(span);
  outerdiv.appendChild(div);
}

container.appendChild(outerdiv);
pending…
1000 createTextNode
var container = document.getElementById('container');
var outerdiv = document.createDocumentFragment();
var i, div, span;
for (i = 0; i < 1000; i++) {
  div = document.createElement('div');
  span = document.createElement('span');
  span.appendChild(document.createTextNode(i));
  div.appendChild(span);
  outerdiv.appendChild(div);
}
container.appendChild(outerdiv);
pending…
1000 element textContent
var container = document.getElementById('container');
var outerdiv = document.createDocumentFragment();
var i, div, span;
for (i = 0; i < 1000; i++) {
  div = document.createElement('div');
  span = document.createElement('span');
  span.textContent = i;
  div.appendChild(span);
  outerdiv.appendChild(div);
}
container.appendChild(outerdiv);
pending…
1000 element innerText
var container = document.getElementById('container');
var outerdiv = document.createDocumentFragment();
var i, div, span;
for (i = 0; i < 1000; i++) {
  div = document.createElement('div');
  span = document.createElement('span');
  span.innerText = i;
  div.appendChild(span);
  outerdiv.appendChild(div);
}
container.appendChild(outerdiv);
pending…
1000 element string innerHTML [concat]
var out = ['<div>']
var i;
for (i = 0; i < 1000; i++) {
  out.push('<div><span>');
  out.push(i);
  out.push('</span></div>');
}
out.push('</div>');

document.getElementById('container').innerHTML = out.join('');
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