Function Loops (v11)

Revision 11 of this benchmark created on


Description

Testing the performance of filtering a list with a given function.

Preparation HTML

// Your standard for loop
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
  // A list to be filtered
  var list = [];
  for (var i = 0; i < 100000; i++) {
   list[i] = i;
  }
  
  // This is the function we will use to filter the list
  var criteria = function(n) {
   return (n % 7 == 0) || (n % 4 == 0);
  }
  
  function standardFilter(array, fn) {
   var results = [];
   for (var i = 0, len = array.length; i < len; i++) {
    if (fn(array[i])) results.push(array[i]);
   }
   return results;
  }


  function standardFilterItem(array, fn) {
   var results = [];
   var item;
   for (var i = 0, len = array.length; i < len; i++) {
    item = array[i];
    if (fn(item)) results.push(item);
   }
   return results;
  }
  
  // MDC Filter Pollyfill:
  if (!Array.prototype.mdcFilter) {
   Array.prototype.mdcFilter = function(fun /*, thisp */ ) {
    "use strict";
  
    if (this === void 0 || this === null) throw new TypeError();
  
    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun !== "function") throw new TypeError();
  
    var res = [];
    var thisp = arguments[1];
    for (var i = 0; i < len; i++) {
     if (i in t) {
      var val = t[i]; // in case fun mutates this
      if (fun.call(thisp, val, i, t)) res.push(val);
     }
    }
  
    return res;
   };
  }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Standard For Loop
var results = standardFilterItem(list, criteria);
ready
Native Filter (If supported)
var results = list.filter(criteria);
ready
Manually Inlined
var results = [];
var item;
for (var i = 0, len = list.length; i < len; i++) {
 item = list[i];
 if ((item % 7 == 0) || (item % 4 == 0)) results.push(item);
}
ready
MDC Filter Polyfill
var results = list.mdcFilter(criteria);
ready
Standard For loop no variable
var results = standardFilter(list, criteria);
ready
use jQuery.grep
var results = $.grep(list, criteria);
ready

Revisions

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