jquery-grep-with-filter (v3)

Revision 3 of this benchmark created by MoonScript on


Description

Comparing jQuery.grep to native Array.filter when looping over an array.

Preparation HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
 
<script>
  (function($){
  // Only check for the existance of Array.filter once
  var filterExists = $.isFunction(Array.prototype.filter);
  
  $.newGrep = function(collection, callback, invert){
    // If this is an array, and Array.filter exists, use it rather than the existing jQuery.grep
    if (filterExists && ($.type(collection) === 'array')) {
      invert = (invert === true);
      return collection.filter(function(item, index){
        return (callback(item, index) !== invert);
      });
    }
    return $.grep(collection, callback);
  };
  
  })(jQuery);
  
  var arrOfNums= [];
  for (var i=0;i<1000;i++) {
    arrOfNums.push(Math.random());
  }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
jQuery.grep
var filteredNums = $.grep(arrOfNums, function(num, idx){
  return (num < 0.5);
});
ready
jQuery.grep with Array.filter
var filteredNums = $.newGrep(arrOfNums, function(num, idx){
  return (num < 0.5);
});
ready
Array.filter
var filteredNums = arrOfNums.filter(function(num, idx){
  return (num < 0.5);
});
ready

Revisions

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

  • Revision 3: published by MoonScript on