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!
Written by Avner Cohen
Related protips
Have a fresh tip? Share with Coderwall community!
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside