for vs forEach (v294)

Revision 294 of this benchmark created by bob on


Description

Is it faster to use the native forEach or just loop with for?

Inspired by Adrian Sutton's tests at: http://www.symphonious.net/2010/10/09/javascript-performance-for-vs-foreach/

This one adds random floating point numbers to see if the loop overhead is significant at all in the face of standard work.

Setup

var i,
        value,
        length,
        values = [],
        sum = 0,
        context = values;
    
    
    for (i = 0; i < 10000; i++) {
        values[i] = Math.random();
    }
    
    function add(val) {
        sum += val;
    }
    
    function my_for_each(A, f)
    {
    
        for(var k = 0, m = A.length; k<m; k++)
             f(A[k], k, A)
    }
    
    
    function my_for_each2(A, f)
    {
    
        for(var k = 0, m = A.length; k<m; k++)
            if(k in A) f(A[k], k, A)
    }
    function my_for_each3(A, f, that)
    {
    
        for(var k = 0, m = A.length; k<m; k++)
            if(k in A) {
                if (that) f.call(that, A[k], k, A)
                else f(A[k], k, A)
            }
    }
    
    function my_for_each4(A, f, that)
    {
    
        for(var k = 0, m = A.length; k<m; k++)
            if(k in A) {
                f.call(that, A[k], k, A)
            }
    }
    var GLOBAL = function () {return this} ();
    var emptyy = {};
    function my_for_each5(A, f, that)
    {
       // if (!that) that = GLOBAL;
        if (!that) that = emptyy;
        that.________ = f;
        for(var k = 0, m = A.length; k<m; k++)
            if(k in A) {
                that.________(A[k], k, A)
            }
        delete that.________; //optional and not always better for perfs
    }

Teardown


    i = 0;
    value = 0;
    length = 0;
    values = [];
    sum = 0;
  

Test runner

Ready to run.

Testing in
TestOps/sec
forEach
values.forEach(add);
ready
for loop, cached length
length = values.length;
for (i = 0; i < length; i++) {
    sum += values[i];
}
ready
for loop, assignment condition
for (i = 0; (value = values[i]) !== undefined; i++) {
    sum += value;
}
ready
forEach without cache
values.forEach(function (val) {
    sum += val;
});
ready
personal foreach
my_for_each(values, function (v) {sum+=v} )
ready
perso2 (more general)
my_for_each2(values, function (v) {sum+=v} )
ready
perso3
my_for_each3(values, function (v) {sum+=v} )
ready
perso4 as in the specs (by use)
my_for_each4(values, function (v) {sum+=v})
ready
perso5
my_for_each5(values, function (v) {sum+=v})
ready

Revisions

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