Function Loops (v3)

Revision 3 of this benchmark created by Adam Sanderson on


Description

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

Preparation HTML

<script>
  var list = [];
  for (var i = 0; i < 500; i++) {
   list[i] = i;
  }
  
  var criteria = function(n) {
   return (n % 7 == 0) || (n % 4 == 0);
  }
  
  // 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 = [];
var item;
for (var i = 0, len = list.length; i < len; i++) {
 item = list[i];
 if (criteria(item)) results.push(item);
}
ready
Countdown Loop
var results = [];
var item;
var len = list.length;

while (--len) {
 item = list[len];
 if (criteria(item)) results.unshift(item);
}
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
Native Filter With Current Context(If supported)
var results = list.filter(criteria, this);
ready
MDC Filter Polyfill
var results = list.mdcFilter(criteria);
ready
Standard For Loop - Explicitly Set Values
var results = [];
var item;
for (var i = 0, len = list.length; i < len; i++) {
 item = list[i];
 // underscore does this instead of push:
 if (criteria(item)) results[results.length] = item;
}
ready

Revisions

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