flatten vs reduce

JavaScript performance comparison

Test case created by Eugene Prystupa

Info

Testing two strategies to get the indexes of items in array that match predicate.

Preparation code

<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min.js"></script>
<script>
Benchmark.prototype.setup = function() {
    var data = _.map(_.shuffle(_.range(40000)), function(i) {
      return {
        a: i,
        b: Math.random(),
        c: Math.random(),
        d: Math.random(),
        e: Math.random(),
        f: Math.random(),
        g: Math.random()
      };
    });
};

Benchmark.prototype.teardown = function() {
    function assert(condition, message) {
        if (!condition) {
            throw Error(message || "Assertion failed");
        }
    }
   
    assert(included.length === 20000, "included length is not right: " + included.length);
};
</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 flatten
var included = _.flatten(_.map(data, function(item, i) {
  return (item.a % 2 === 0) ? [i] : [];
}), true);
pending…
Using reduce
var included = _.reduce(data, function(memo, item, i) {
  if (item.a % 2 === 0) memo.push(i);
  return memo;
}, []);
pending…
using plain javascript with for loop
var included = [];
var len = data.length;
for (var i = 0; i < len; i++) {
  if (data[i].a % 2 === 0) included.push(i);
}
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