underscore.js template vs. string concatenation vs. sprintf

JavaScript performance comparison

Revision 6 of this test case created

Preparation code

<script src="http://documentcloud.github.com/underscore/underscore-min.js">
</script>
<script src="https://rawgithub.com/alexei/sprintf.js/master/src/sprintf.min.js">
</script>
<script>
Benchmark.prototype.setup = function() {
    var nonCachedTemplate = "body.search #main, body.project #main, #sidebar { height: {{ height }}px width: {{ width }}px zindex: {{ zindex }}px minwidth: {{ minwidth }}px minheight: {{ minheight }}px }";
   
    var template = _.template("body.search #main, body.project #main, #sidebar { height: {{ height }}px width: {{ width }}px zindex: {{ zindex }}px minwidth: {{ minwidth }}px minheight: {{ minheight }}px }");
   
    var templateScopeContext = _.template("body.search #main, body.project #main, #sidebar { height: {{ data.height }}px width: {{ data.width }}px zindex: {{ data.zindex }}px minwidth: {{ data.minwidth }}px minheight: {{ data.minheight }}px }");
   
    var format = "body.search #main, body.project #main, #sidebar { height: %(height)spx width: %(width)spx zindex: %(zindex)spx minwidth: %(minwidth)spx minheight: %(minheight)spx }";
   
    var height = 820;
    var width = "720.00";
    var zindex = "two hundred";
    var minwidth = [420, "minwidth", new Date(), {}];
    var minheight = -24;
    var stringPushCatArry = [];
};
</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
string concatenation
"body.search #main, body.project #main, #sidebar { height: " + height + "px width: " + width + "px zindex: " + zindex + "px minwidth: " + minwidth[2] + "px minheight: " + minheight + "px}";
pending…
underscore.js template
template({
  height: height,
  width: width,
  zindex: zindex,
  minwidth: minwidth[2],
  minheight: minheight
})
pending…
underscore.js template with data
templateScopeContext({
  height: height,
  width: width,
  zindex: zindex,
  minwidth: minwidth[2],
  minheight: minheight
})
pending…
none cached
_.template(nonCachedTemplate, {
  height: height,
  width: width,
  zindex: zindex,
  minwidth: minwidth[2],
  minheight: minheight
})
pending…
push and join array
var myArray = ["body.search #main, body.project #main, #sidebar { height: ", height, "px width: ", width, "px zindex: ", zindex, "px minwidth: ", minwidth[2], "px minheight: ", minheight, "px}"];

myArray.join();
pending…
sprintf
sprintf(format, {
  height: height,
  width: width,
  zindex: zindex,
  minwidth: minwidth[0],
  minheight: minheight
});
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