JavaScript Templating

JavaScript performance comparison

Test case created by Andrew Hedges

Preparation code

<script type="text/html" id="smpl_tmpl">
Hello, <%=name%>
</script>

<script type="text/html" id="inner_tmpl">
Life is but a <%=dream%>
</script>

<script type="text/html" id="outer_tmpl">
How about this for a song? <%=inner%>
</script>

<script>
  /*  Simple HTML templates in pure JavaScript
      Andrew Hedges, andrew@hedges.name
      http://andrew.hedges.name/
      http://snipt.org/rpp
   
      Usage:
  
      var myTemplate = new Template('#{greeting}, #{name}!')
      var myOutput = myTemplate.evaluate({
          greeting : 'Hello',
          name : 'world',
      })
      alert(myOutput) // "Hello, world!"
  
  */
  function Template(str) {
   this.rgx = /#\{([^{}]*)\}/g;
   this.str = str || '';
  }
  // END: Template constructor
  Template.prototype.evaluate = function(vals) {
   var repr;
   vals = vals || {};
   repr = function(str, match) {
    return 'string' === typeof vals[match] || 'number' === typeof vals[match] ? vals[match] : str;
   };
   return this.str.replace(this.rgx, repr);
  };
  // END: Template.prototype.evaluate
  var smpl_tmpls = {
   simple: new Template('Hello, #{name}!'),
   inner: new Template('Life is but a #{dream}'),
   outer: new Template('How about this for a song? #{inner}')
  };
  
  // Simple JavaScript Templating
  // John Resig - http://ejohn.org/ - MIT Licensed
  (function() {
   var cache = {};
  
   this.tmpl = function tmpl(str, data) {
    // Figure out if we're getting a template, or if we need to
    // load the template - and be sure to cache the result.
    var fn = !/\W/.test(str) ? cache[str] = cache[str] || tmpl(document.getElementById(str).innerHTML) :
  
    // Generate a reusable function that will serve as a template
    // generator (and which will be cached).
    new Function("obj", "var p=[],print=function(){p.push.apply(p,arguments);};" +
  
    // Introduce the data as local variables using with(){}
    "with(obj){p.push('" +
  
    // Convert the template into pure JavaScript
    str.replace(/[\r\t\n]/g, " ").split("<%").join("\t").replace(/((^|%>)[^\t]*)'/g, "$1\r").replace(/\t=(.*?)%>/g, "',$1,'").split("\t").join("');").split("%>").join("p.push('").split("\r").join("\\'") + "');}return p.join('');");
  
    // Provide some basic currying to the user
    return data ? fn(data) : fn;
   };
  })();
</script>
    

Preparation code output

Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Hedges' Simple Templates
var result1 = smpl_tmpls.simple.evaluate({
 name: 'Andrew'
});

var result2 = smpl_tmpls.outer.evaluate({
 inner: smpl_tmpls.inner.evaluate({
  dream: 'dream'
 })
});
pending…
Resig's Micro Templating
var result1 = tmpl('smpl_tmpl', {
 name: 'Andrew'
});

var result2 = tmpl('outer_tmpl', {
 inner: tmpl('inner_tmpl', {
  dream: 'dream'
 })
});
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.

0 Comments