innerHTML vs createElement test

JavaScript performance comparison

Revision 29 of this test case created

Preparation code

<div id="container">
</div>
<script>
Benchmark.prototype.setup = function() {
    container = document.getElementById('container')
    container.innerHTML = '';
    escapeHTML = function(text){
      return String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
    }
};

Benchmark.prototype.teardown = function() {
    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
var html = ''

for (var i = 0; i < 100; i++) {
  html += '<div><span>' + escapeHTML(i) + '</span></div>'
}

container.innerHTML = html

var nodes = []
var node = container.firstChild
do{
  nodes.push(container[i])
} while( node = node.nextSibling )
pending…
fragment + innerHTML
var fragment = document.createDocumentFragment();
var nodes = []

for (var i = 0; i < 100; i++) {
  var div = document.createElement("div")
  var span = document.createElement("span")
  span.innerHTML = escapeHTML(i)
  div.appendChild(span)
  fragment.appendChild(div)
  nodes.push(div)
}

container.appendChild(fragment)
pending…
fragment + textContent
var fragment = document.createDocumentFragment();
var nodes = []

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

container.appendChild(fragment)
pending…
fragment + innerText
var fragment = document.createDocumentFragment();
var nodes = []

for (var i = 0; i < 100; i++) {
  var div = document.createElement("div")
  var span = document.createElement("span")
  span.innerText = i
  div.appendChild(span)
  fragment.appendChild(div)
  nodes.push(div)
}

container.appendChild(fragment)
pending…
fragment + textNode
var fragment = document.createDocumentFragment();
var nodes = []

for (var i = 0; i < 100; i++) {
  var div = document.createElement("div")
  var span = document.createElement("span")
  var text = document.createTextNode(String(i))
  span.appendChild(text)
  div.appendChild(span)
  fragment.appendChild(div)
  nodes.push(div)
}

container.appendChild(fragment)
pending…
insertAdjacentHTML
var nodes = []
for (var i = 0; i < 100; i++) {
  container.insertAdjacentHTML('beforeend', '<div><span>' + escapeHTML(i) + '</span></div>')
  nodes.push(container.lastChild)
}
 
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