Functional Iterators vs For Loop (Sum) (v3)

Revision 3 of this benchmark created by Teja on


Description

Trying to see how much overhead the functional iterators from ECMA5 have over doing things the old fashioned way with a for loop.

Each test case is doing a boring old sum.

Underscore uses the native version of a function if it exists, but is probably doing a few checks and falls back on other implementations.

Native functions will cause errors on browsers where they don't exist.

Preparation HTML

<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.2.2/underscore-min.js">
</script>
<script>
  array = [];
  i = 5000;
  while (i--) {
    array.push(Math.floor(Math.random() * 100));
  }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
For Loop
var sum = 0,
    i = 0,
    l = array.length;

for (i; i < l; i++) {
  sum += array[i];
}
ready
For In
var i, sum = 0;
for (i in array) {
  if (array.hasOwnProperty(i)) {
    sum += array[i];
  }
}
ready
For In (Unprotected)
var i, sum = 0;
for (i in array) {
  sum += array[i];
}
ready
ForEach
var sum = 0,
    forfunc = function(x) {
    sum += x;
    };

_.each(array, forfunc);
ready
Reduce
var sum = 0,
    reducefunc = function(prev, current, i, arr) {
    return prev + current;
    };

sum = _.reduce(array, reducefunc, 0);
ready
ReduceRight
var sum = 0,
    reducefunc = function(prev, current, i, arr) {
    return prev + current;
    };

sum = _.reduceRight(array, reducefunc, 0);
ready
Object.keys
var sum = 0,
    i = 0,
    keys = Object.keys(array),
    l = keys.length;

for (i; i < l; i++) {
  sum += array[keys[i]];
}
ready
Native ForEach
var sum = 0,
    forfunc = function(x) {
    sum += x;
    };

array.forEach(forfunc);
ready
Native Reduce
var sum = 0,
    reducefunc = function(prev, current, i, arr) {
    return prev + current;
    };

sum = array.reduce(reducefunc, 0);
ready
Native ReduceRight
var sum = 0,
    reducefunc = function(prev, current, i, arr) {
    return prev + current;
    };

sum = array.reduceRight(reducefunc, 0);
ready

Revisions

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