handlebars each vs concatenation vs array join

JavaScript performance comparison

Test case created

Preparation code

<script src="//cloud.github.com/downloads/wycats/handlebars.js/handlebars-1.0.rc.1.js"></script>
<script src="//underscorejs.org/underscore-min.js"></script>
<script>
Benchmark.prototype.setup = function() {
    var optionTemplateString = '<option value="{{value}}">{{label}}</option>';
    optionTemplate = Handlebars.compile(optionTemplateString);
    optionsTemplate = Handlebars.compile(
        '{{#each options}}' + optionTemplateString + '{{/each}}');
   
    target = {options:[]};
    resultRegex = /^<option.*<\/option>$/;
    var pad = function (number, length) {
        var str = '' + number;
        while (str.length < length) {
            str = '0' + str;
        }
    }
   
    var suffix = '';
    for (var i = 0; i < 10000; i++) {
        suffix = pad(i, 5);
        target.options.push({value:'foo'+suffix,label:'bar'+suffix});
    }
};

Benchmark.prototype.teardown = function() {
    if (!resultRegex.test(result)) {
        throw new Error('Unexpected output');
    }
};
</script>

Preparation code output

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Handlebars each
result = optionsTemplate(target);
pending…
String concatenation
var options = target.options;
var length = options.length;
result = '';
for (var i = 0; i < length; i++) {
    result += optionTemplate(options[i]);
}
pending…
Array join
var options = target.options;
var length = options.length;
result = [];
for (var i = 0; i < length; i++) {
    result.push(optionTemplate(options[i]));
}
result = result.join('');
pending…
Underscore each
result = _.map(target.options, optionTemplate).join('');
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. Here’s a list of current revisions for this page:

0 comments

Add a comment