handlebars vs replace (v3)

Revision 3 of this benchmark created on


Description

Comparation between String.replace and handlebars compiled tempaltes

Preparation HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.min.js"></script>
<script id="tpl" type="template/handlebars">
  Hello {{name}}!
</script>

Setup

var templateHTML = $('#tpl').html();
    var corrected = document.getElementById("tpl").innerHTML;
    var data = {name: 'Fer'};
    
    // Handlebars template function
    var templateHandlebars = Handlebars.compile(templateHTML);
    
    // Replace based templating
    function templateReplace(tmpl, vals) {
                var rgxp, repr, noEscapeRgxp;
    
                // default to doing no harm
                tmpl = tmpl || '';
                vals = vals || {};
    
                // regular expression for matching our placeholders; e.g., #{my-cLaSs_name77}
                rgxp = /#\{([^{}]*)}/g;
                // regex for text (markup) that should not be escaped; e..g., #{{html_content}}
                noEscapeRgxp = /#\{{([^{}]*)}}/g;
    
                // function to making replacements
                repr = function (str, match) {
                    var value = vals[match];
                    return (typeof value === 'string' || typeof value === 'number') ? htmlEncode(value) : str;
                };
    
                // non-escaped text (HTML)
                noEscapeRepr = function (str, match) {
                    var value = vals[match];
                    return (typeof value === 'string' || typeof value === 'number') ? value : str;
                };
    
                return tmpl.replace(rgxp, repr).replace(noEscapeRgxp, noEscapeRepr);
    }

Test runner

Ready to run.

Testing in
TestOps/sec
Replace based template engine
var result = templateReplace(corrected, data);
ready
Handlebars template engine
var result = templateHandlebars(data);
ready

Revisions

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