Render Template From DOM Select vs Cache

JavaScript performance comparison

Test case created by Derick Bailey


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

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

<script id="test-template" type="text/template">
    this is <div class="foo">some html</div>
    <li>with data
    <li>and items
<script src=""></script>
<script src=""></script>
<div id="html-output-goes-here"></div>
Benchmark.prototype.setup = function() {
    this.cachedItem = $("#test-template");
    this.cachedTemplate = _.template(this.cachedItem.html());
    this.output = $("#html-output-goes-here");

Benchmark.prototype.teardown = function() {
    delete this.cachedItem;
    delete this.cachedTemplate;

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
var html = this.cachedTemplate();
var uncachedItem = $("#test-template");
var uncachedTemplate = _.template(uncachedItem.html());
var html = uncachedTemplate();

Compare results of other browsers


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:

1 comment

guest commented :

I doubt the cost is not because of the dom selection, but due to the compilation of template again and again var uncachedTemplate = _.template(uncachedItem.html());

Comment form temporarily disabled.

Add a comment