Function Loops (v5)

Revision 5 of this benchmark created on


Description

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

Preparation HTML

<script>
  // A list to be filtered
  var list = [];
  for (var i = 0; i < 500; 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);
  }
  
  // Your standard for loop
  
  function standardFilter(array, fn) {
   var results = [],
       i = 0,
       item, len = array.length;
  
   for (; i < len;) {
    item = array[i++];
    if (fn(item)) results[results.length] = 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 = standardFilter(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
Manually Inlined 2
var results = [],
    i = 0,
    len = list.length,
    item;

for (; i < len;) {
 item = list[i++];
 if ((item % 7 === 0) || (item % 4 === 0)) results[results.length] = item;
}
ready

Revisions

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