JavaScript Templating

Benchmark created by Andrew Hedges on


Description

Testing the relative speed of JavaScript template solutions. Feel free to add more!

Preparation HTML

<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>

Test runner

Ready to run.

Testing in
TestOps/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'
 })
});
ready
Resig's Micro Templating
var result1 = tmpl('smpl_tmpl', {
 name: 'Andrew'
});

var result2 = tmpl('outer_tmpl', {
 inner: tmpl('inner_tmpl', {
  dream: 'dream'
 })
});
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by Andrew Hedges on
  • Revision 2: published by Weiss I Nicht on