Last Updated: February 25, 2016
·
1.03K
· avnerner

Microbenchmarking: Looping in Javascript

It's mythbuster time .. or is it?

We all heard that in a for loop, it is better to externalise and cache the arr.length instead of accessing it with each loop.
Is it really?

I have created this small JsPerf sample to test this on multiple browsers and compare the results.
http://jsperf.com/best-looping-methods

Results are quite interesting:
1. In all browsers, a for : in syntax is nearly 90% slower than other methods !
2. In Chrome, even if you are microbanchmarking, variations is negligible (for : in aside).
3. FireFox on for loops is nearly twice as fast as Chrome!
4. Only Safari does not automatically cache the arr.length, which than impacts performances.

Bottom line, when coding a critical path in your program, it may actually does matter, so you'd better cache that length!