innerHTML vs DOM methods

JavaScript performance comparison

Revision 3 of this test case created by nwellcome

Info

See comments @ http://stackoverflow.com/questions/7099258

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<ol id="list">
</ol>
<script>
  var html = "";
  for (i = 0; i <= 2000; i++) {
    html += "<li><a href='#'>Hi</a></li>";
  }
 
  var fragment = document.createDocumentFragment();
  var list = document.getlementById("list");
</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
list.innerHTML = html;
pending…
DOM methods
var anchor;
var listElement;
for (var i = 0; i <= 2000; i++) {
  listElement = document.createElement("li");
  anchor = document.createElement("a");
  anchor.innerHTML = "Hi";
  anchor.href = "#";
  listElement.appendChild(anchor);
  list.appendChild(listElement);
}
pending…
Document Fragment
for (i = 0; i <= 200; i++) {
  fragment.appendChild($(document.createElement('li')).append($(document.createElement('a')).text('Hi').attr({
    href: 'foobar'
  })).get(0));
}
list.appendChild(fragment);
pending…
Document Fragment, no jQuery
var anchor;
var listElement;
for (i = 0; i <= 200; i++) {
  listElement = document.createElement("li");
  anchor = document.createElement("a");
  anchor.innerHTML = "Hi";
  anchor.href = "#";
  listElement.appendChild(anchor);
  fragment.appendChild(listElement);
}
list.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