Render Template From DOM Select vs Cache vs HTML Cache

JavaScript performance comparison

Revision 11 of this test case created and last updated

Info

This test was spawned by some discussion in a StackOverflow thread:

http://stackoverflow.com/questions/9833312/how-do-i-properly-store-a-javascript-template-so-that-it-isnt-instantiated-mul

The purpose is to test the speed of rendering an underscore.js template when selecting the template from the DOM every time, vs selecting it once and re-rendering the cached template every time.

Preparation code

<div id='tp'>
  <p> this is <div class = "foo"> some html </div>
  </p> <ul><li> with data <li> and items <li> etc </ul>
</div>

<script id="test-template" type="text/template">
  < p > this is < div class = "foo" > some html < /div>
  </p > < ul > < li > with data < li > and items < li > etc < /ul>
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script src="http://documentcloud.github.com/underscore/underscore-min.js">
</script>

<div id="html-output-goes-here">
</div>
<script>
Benchmark.prototype.setup = function() {
    this.cachedItem = $("#test-template");
    this.cachedHtml = this.cachedItem.html();
    this.cachedTemplate = _.template(this.cachedHtml);
    this.output = $("#html-output-goes-here");
   
    window.domout = document.getElementById('html-output-goes-here');
    window.cT = document.getElementById('tp');
   
};

Benchmark.prototype.teardown = function() {
    delete this.cachedItem;
    delete this.cachedTemplate;
    window.domout.innerHTML = '';
};
</script>

Preparation code output

this is

some html

  • with data
  • and items
  • etc

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Template-Cached
var html = this.cachedTemplate();
this.output.html(html);
pending…
Non-Cached
var uncachedItem = $("#test-template");
var uncachedTemplate = _.template(uncachedItem.html());
var html = uncachedTemplate();
this.output.html(html);
pending…
DOM-Item-Cached
var itemCachedTemplate = _.template(this.cachedItem.html());
var html = itemCachedTemplate();
this.output.html(html);
pending…
Html-Cached
var itemCachedTemplate = _.template(this.cachedHtml);
var html = itemCachedTemplate();
this.output.html(html);
pending…
Without compiling
this.output.html(this.cachedHtml);
pending…
domout.appendChild( cT.cloneNode(true) );
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