Precompiled templates (v2)

Revision 2 of this benchmark created by Vegard Larsen on


Description

Tests precompiled templates versus "standard" JavaScript micro-templating. One of the tests assumes you can pre-load the template, another that you are loading different templates, and thus need to use $('#sometemplate').html() to find the template each time.

Preparation HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

<script type="text/html" id="tpl">
<tr>
  <td><#= sName #></td>
  <td><#= sRole #></td>
  <td><#= sPhone #></td>
</tr>
</script>
<script>
  /* From http://www.west-wind.com/weblog/posts/509108.aspx */
  (function() {
   var _tmplCache = {};
   this.parseTemplate = function(str, data) {
    /// <summary>
    /// Client side template parser that uses &lt;#= #&gt; and &lt;# code #&gt; expressions.
    /// and # # code blocks for template expansion.
    /// NOTE: chokes on single quotes in the document in some situations
    ///       use &amp;rsquo; for literals in text and avoid any single quote
    ///       attribute delimiters.
    /// </summary>    
    /// <param name="str" type="string">The text of the template to expand</param>    
    /// <param name="data" type="var">
    /// Any data that is to be merged. Pass an object and
    /// that object's properties are visible as variables.
    /// </param>    
    /// <returns type="string" />  
    var err = "";
    try {
     var func = _tmplCache[str];
     if (!func) {
      var strFunc = "var p=[],print=function(){p.push.apply(p,arguments);};" + "with(obj){p.push('" +
  
      str.replace(/[\r\t\n]/g, " ").replace(/'(?=[^#]*#>)/g, "\t").split("'").join("\\'").split("\t").join("'").replace(/<#=(.+?)#>/g, "',$1,'").split("<#").join("');").split("#>").join("p.push('") + "');}return p.join('');";
  
      //alert(strFunc);
      func = new Function("obj", strFunc);
      _tmplCache[str] = func;
     }
     return func(data);
    } catch (e) {
     err = e.message;
    }
    return "< # ERROR: " + err.htmlEncode() + " # >";
   }
  })();
  
  var person = {
   sName: "John Doe",
   sRole: "Administrator",
   sPhone: "123-555-1234"
  };
  
  (function() {
   window.templates = {
    UserRow: function(o) {
     var p = [];
     with(o) {
      p.push('<tr><td>', sName, '</td><td>', sRole, '</td><td>', sPhone, '</td></tr>');
     }
     return p.join('');
    }
   };
  })();
  var tpl = $("#tpl").html();
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Uncompiled
var html = parseTemplate(tpl, person);
ready
Precompiled
var html = templates.UserRow(person);
ready
Uncompiled with jQuery lookup
var tpl = $("#tpl").html();
var html = parseTemplate(tpl, person);
ready

Revisions

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

  • Revision 1: published by Vegard on
  • Revision 2: published by Vegard Larsen on