DOM vs innerHTML based Templating

JavaScript performance comparison

Revision 478 of this test case created by Jeremy Ashkenas

Info

Underscore Templates vs. raw DOM manipulation.

Preparation code

<script src="http://documentcloud.github.com/underscore/underscore.js"></script>

<div id="target"></div>

<script> 
  window.target = document.getElementById("target");

  window.underscoreTemplate = _.template("<div><h1 class='header'><%= data.header %></h1><div class='a'><%= data.a %></div><div class='b'><%= data.b %><div class='c'><%= data.c %><div class='d'><%= data.d %><div class='e'><%= data.e %><div class='f'><%= data.f %></div></div></div></div></div></div>", null, {variable: 'data'});
 
  window.sharedVariables = {
   header: "Header",
   a: 'aaa',
   b: 'bbb',
   c: 'ccc',
   d: 'ddd',
   e: 'eee',
   f: 'fff'
  };
</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
Underscore.js Template
target.innerHTML = underscoreTemplate(sharedVariables);
 
pending…
DOM Manipulation
var template = document.createElement('div');
var header = document.createElement('h1');
header.className = 'header';
header.textContent = sharedVariables.header;
var a = document.createElement('div');
a.className = 'a';
a.textContent = sharedVariables.a;
var b = document.createElement('div');
b.className = 'b';
b.textContent = sharedVariables.b;
var c = document.createElement('div');
c.className = 'c';
c.textContent = sharedVariables.c;
var d = document.createElement('div');
d.className = 'd';
d.textContent = sharedVariables.d;
var e = document.createElement('div');
e.className = 'e';
e.textContent = sharedVariables.e;
var f = document.createElement('div');
f.className = 'f';
f.textContent = sharedVariables.f;

template.appendChild(header);
template.appendChild(a);
a.appendChild(b);
b.appendChild(c);
c.appendChild(d);
d.appendChild(e);
e.appendChild(f);

while (target.firstChild) {
  target.removeChild(target.firstChild);
}
target.appendChild(template);
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