lodash: map+compact vs filter+map vs reduce (v4)

Revision 4 of this benchmark created on


Preparation HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js"></script>

Setup

var a = [];

    for(var i = 0; i < 200; i++){
      a.push({
        i: i,
        even: i % 2 === 0
      })
    }

Test runner

Ready to run.

Testing in
TestOps/sec
filter & map
_.filter(a, function(item) {
  return item.even;
}).map(function(item) {
  item.pow = item.i * item.i;
  return item;
});
ready
compact & map
_.compact(_.map(a, function(item) {
  if (item.even) {
    item.pow = item.i * item.i;
    return item;
  }
}));
ready
reduce
var resIndex = -1;
_.reduce(a, function(acc, cur) {
  if (cur.even) {
    cur.pow = cur.i * cur.i;
    acc[++resIndex]=cur;
  }
  return acc;
}, []);
ready
Manual reduce
var index = -1,
    length = a ? a.length : 0,
    resIndex = -1,
    result = [];

while (++index < length) {
    var cur = a[index];
    if (cur.even) {
        result[++resIndex] = cur;
        cur.pow = cur.i * cur.i;
    }
}
    
ready

Revisions

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