innerHTML vs createElement test

JavaScript performance comparison

Revision 21 of this test case created

Info

try documentFragment

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<div id="container"></div>
<script>
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
innerHTML, string concat
var innerHTMLstr = '<div>';
for (var i = 0; i < 100; i++) {
  innerHTMLstr += '<div><span>' + i + '</span></div>';
}
innerHTMLstr += '</div>';

document.getElementById('container').innerHTML = innerHTMLstr;
pending…
innerHTML, Array.join()
var innerHTMLarray = ['<div>'];
for (var i = 0; i < 100; i++) {
  innerHTMLarray.push('<div><span>', i, '</span></div>');
}
innerHTMLarray.push('</div>');

document.getElementById('container').innerHTML = innerHTMLarray.join('');
pending…
createElement, bulk add
var container = document.getElementById('container');
var outerdiv = document.createElement('div');

for (var i = 0; i < 100; i++) {
  var div = document.createElement('div');
  var span = document.createElement('span');

  span.textContent = i;
  div.appendChild(span);
  outerdiv.appendChild(div);

}

container.appendChild(outerdiv);
pending…
Clone
var container = document.getElementById('container');
var outerdiv = document.createDocumentFragment();
var i, div, span;
var p;

div = document.createElement('div');
span = document.createElement('span');
div.appendChild(span);

for (i = 0; i < 100; i++) {
  p = div.cloneNode(true);
  p.firstChild.textContent = i;
  outerdiv.appendChild(p);
}

container.appendChild(outerdiv);
pending…
CreateElementV2
var container = document.getElementById('container');
var outerdiv = document.createElement('div');

var dce = document.createElement.bind(document)
var d = document
var ce = document.createElement
document.ce = document.createElement
for (var i = 0; i < 100; i++) {
  var div = ce.call(d,'div');
  var span = ce.call(d,'span');

  span.textContent = i;
  div.appendChild(span);
  outerdiv.appendChild(div);

}

container.appendChild(outerdiv);
pending…
documentFragment
var outerdiv = document.getElementById('container'),
    fragment = document.createDocumentFragment();

for (var i = 0; i < 100; i++) {
    var span = document.createElement('span');
        span.textContent = i;
   
    var div = document.createElement('div');
        div.appendChild(span);
   
    fragment.appendChild(div);
}

outerdiv.appendChild(fragment)
 
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