underscore.js reject vs native (v11)

Revision 11 of this benchmark created by Patrik Affentranger on


Description

Underscore.js has a reject function which excludes list items that match a criterion. This is to explore whether there's a significant performance difference between this function and a native implementation.

Preparation HTML

<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.1/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
native-code
function native_reject(contacts) {
  results = [];
  for (var i = 0; i < contacts.length; i++) {
    if (contacts[i].city !== 'Boulder') results.push(contact);
  }
  return results;
}
boulder['native-code'] = native_reject(contacts);
ready
native-filter
function native_filter(contacts) {
  results = [];
  newIndex = -1;
  for (var i = 0; i < contacts.length; i++) {
    if (contacts[i].city !== 'Boulder') {
      ++newIndex;
      results[newIndex] = contact;
    }
  }
  return results;
}
boulder['native-code'] = native_filter(contacts);
ready

Revisions

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