26-04-2009

Array iteration in JavaScript

Ajaxian

Ajaxian posted a very interesting article this week on different syntax options for array iterations in javascript.

View the Ajaxian article on array iteration syntax here.

Although to some perhaps a somewhat trivial subject to focus on, it's also so common a practice in larger javascript apps that the methods used for it can potentially become a major influence on total performance. Thus what is especially interesting here are the differences that can be measured in speed arising from each method. These can be quite surprising as exemplified in the test results put forward by one of the commentators in the article.

I've copied these here for quick reference. (source: http://nerget.com/jstests/performance/array-iteration.html)

Of course these results may vary a lot from browser to browser. So before relying on these test 'm in different significant browser and platform combinations.

nopIteration : 61ms
function nopIteration(a, f) {
    var start = new Date;
    for (var i = 0; i < a.length; i++) {
    }
    var end = new Date;
    return end - start;
}
 
 
nopIteration0 : 28ms
function nopIteration0(a, f) {
    var start = new Date;
    var i = a.length;
    while (i--) {
    }
    var end = new Date;
    return end - start;
}
 
 
nopIteration1 : 43ms
function nopIteration1(a, f) {
    var start = new Date;
    var l = a.length;
    for (var i = 0; i < l; i++) {
    }
    var end = new Date;
    return end - start;
}
 
 
simpleIteration : 763ms
function simpleIteration(a, f) {
    var start = new Date;
    for (var i = 0; i < a.length; i++) {
        f(i);
    }
    var end = new Date;
    return end - start;
}
 
 
forEachIteration : 738ms
function forEachIteration(a, f) {
    var start = new Date;
    a.forEach(f);
    var end = new Date;
    return end - start;
}
 
 
forInIteration : 2239ms
function forInIteration(a, f) {
    var start = new Date;
    for (var i in a) {
        f(a[i]);
    }
    var end = new Date;
    return end - start;
}
 
 
 
 

Comments:

Your comment:

»

 

[x]