underscore.js filter vs reject (v5)

Revision 5 of this benchmark created on


Description

Underscore.js has a filter function (aliased to select) which uses native filter if it's available. It also has a reject function which returns the inverse results; however it doesn't use native filter. This is to explore whether there's a significant performance difference.

Preparation HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min.js"></script>

Setup

window.contacts = [];
    
    var contact;
    
    function getRandomInt (min, max) {
      return Math.floor(Math.random() * (max - min + 1)) + min;
    }
    
    for (var i=0; i < 5000; i++) {
      contact = {};
      contact.firstName = 'firstName' + getRandomInt(1, 500);
      contact.lastName = 'lastName' + getRandomInt(1, 500);
      contact.city = ["Boulder", "Denver", "Denver", "Golden"][getRandomInt(0, 3)];
      contact.state = "CO";
      contacts.push(contact);
    }
    
    var boulder = window.boulder = window.boulder || {};

Test runner

Ready to run.

Testing in
TestOps/sec
filter
boulder['filter'] = _.filter(contacts, function(contact) {
  return contact.city === 'Boulder';
});
ready
reject
boulder['reject'] = _.reject(contacts, function(contact) {
  return contact.city !== 'Boulder';
});
ready
filter-negated
function negate(fn) {
  return function() {
    return !fn.apply(this, arguments);
  };
}

boulder['filter-negated'] = _.filter(contacts, negate(function(contact) {
  return contact.city !== 'Boulder';
}));
ready
where
boulder['where'] = _.where(contacts, { city: 'Boulder'});
ready

Revisions

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