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?
The absolute fastest way to loop through a javascript array is:
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:
It caches the length and is much shorter to write. But it will iterate over the array in reverse order.
http://jsperf.com/caching-array-length/60
The latest revision of test, which I prepared (by reusing older one), shows one thing.
Caching length is not that much important, but it does not harm.
Every first run of the test linked above (on freshly opened tab) gives best results for the last 4 snippets (3rd, 5th, 7th and 10th in charts) in Chrome, Opera and Firefox in my Debian Squeeze 64-bit (my desktop hardware). Subsequent runs give quite different result.
Performance-wise conclusions are simple:
!==
instead of<
.shift()
-ing array is also efficient.tl;dr
Nowadays (2011.10) below pattern looks to be the fastest one.
Mind that caching
arr.length
is not crucial here, so you can just test fori !== arr.length
and performance won't drop, but you'll get shorter code.PS: I know that in snippet with
shift()
its result could be used instead of accessing 0th element, but I somehow overlooked that after reusing previous revision (which had wrong while loops), and later I didn't want to lose already obtained results.Try this:
I have tried some other ways to iterate a huge array and found out that halving the array length and then iterating both halves in a single loop is faster. This performance difference can be seen while processing huge arrays.
Some performance comparison (using timer.js) between the cached length for-loop VS the above method.
http://jsfiddle.net/tejzpr/bbLgzxgo/
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
I would say this is definitely a case where I applaud JavaScript engine developers. A run time should be optimized for clarity, not cleverness.