What's the fastest way to loop through an array in JavaScript?

I learned from books that you should write for loop like this:

for(var i=0, len=arr.length; i < len; i++){
    // blah blah
}

so the arr.length will not be calculated each time.

Others say that the compiler will do some optimization to this, so you can just write:

for(var i=0; i < arr.length; i++){
    // blah blah
}

I just want to know which is the best way in practice?


After performing this test with most modern browsers...

http://jsben.ch/#/y3SpC

Currently , the fastest form of loop (and in my opinion the most syntactically obvious).

a standard for loop with length caching

for (var i = 0, len = myArray.length; i < len; i++) {

}

I would say this is definitely a case where I applaud JavaScript engine developers. A run time should be optimized for clarity , not cleverness.


The absolute fastest way to loop through a javascript array is:

var len = arr.length;
while (len--) {
    // blah blah
}

See http://blogs.oracle.com/greimer/entry/best_way_to_code_a for a full comparison


If the order is not important, I prefer this style:

for(var i = array.length; i--; )

It caches the length and is much shorter to write. But it will iterate over the array in reverse order.

链接地址: http://www.djcxy.com/p/4198.html

上一篇: Javascript中奇怪的行为增强了for ... in循环

下一篇: 在JavaScript中循环数组的最快方法是什么?