_.reduce vs _.map and .join

JavaScript performance comparison

Test case created by wilfred

Preparation code

<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.3/underscore-min.js">
</script>
<script>
Benchmark.prototype.setup = function() {
    var strings = ["hello", "goodbye", "the quick brown fox", "blah blah", "etc"];
    var objectList = []
    for (var i = 0; i < 1000; i++) {
      var randomString = strings[_.random(strings.length - 1)];
      objectList.push({
        string: randomString,
        date: new Date()
      });
    }
};
</script>

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Using reduce
var finalString = _.reduce(objectList, function(memo, dataPair) {
  return memo + dataPair.date.toDateString() + dataPair.string;
}, "");
pending…
Using map and join
var mappedStrings = _.map(objectList, function(dataPair) {
  return dataPair.date.toDateString() + dataPair.string;
});
var finalString = mappedStrings.join("");
pending…

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

Compare results of other browsers

0 comments

Add a comment