Template vs concatanation (v3)

Revision 3 of this benchmark created on


Preparation HTML

<script>
  var template = '<tr><td>{title}</td><td>{type}</td><td><a href="tags/{tag}">{tag}</a></td><td>{created_at}</td></tr>';
  
  var data = {
   title: 'title',
   type: 'type',
   tag: 'tag',
   created_at: 'created_at'
  };
  
  function processTemplate1(template) {
   if (typeof template === 'object') {
    for (var i in template)
    template[i] = processTemplate1(template[i]);
   }
   else if (typeof template === 'string') {
    template = template.replace(/[\n'\\]/g, '\\$&');
    template = template.replace(/\{(\w*)\}/g, function(str, key) {
     return "'+d['" + key + "']+'";
    });
    return new Function("d", "return '" + template + "'");
   }
  
   return template;
  }
  
  function processTemplate2(template) {
   if (typeof template === 'object') {
    for (var i in template)
    template[i] = processTemplate2(template[i]);
   }
   else if (typeof template === 'string') {
    template = template.replace(/[\n'\\]/g, '\\$&');
    template = template.replace(/\{(\w*)\}/g, function(str, key) {
     return "'+d." + key + "+'";
    });
    return new Function("d", "return '" + template + "'");
   }
  
   return template;
  }
  
  var template1 = processTemplate1(template);
  var template2 = processTemplate2(template);
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Concatenation
var output = '<tr><td>' + data.title + '</td><td>' + data.type + '</td><td><a href="tags/' + data.tag + '">' + data.tag + '</a></td><td>' + data.created_at + '</td></tr>';
ready
Template1
var output = template1(data);
ready
Template2
var output = template2(data);
ready

Revisions

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