Search code examples
javascriptperformanceloops

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?


Solution

  • After performing this test with most modern browsers: https://jsben.ch/wY5fo

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

    A standard for-loop with length caching

    var i = 0, len = myArray.length;
    while (i < len) {
        // your code
        i++
    }
    

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