JS For Loop Code Performance



    Perfomance is always the keyword! Every single website strives for being fast - lightning fast! Faster the site, better is the user interaction and better is the conversion. I face this challenge everyday to make sites faster and in the process I ended up testing the 'for' loop with different conditions and I am sharing it here. All observations are a result of running multiple tests for the same set of data.

Regular For Loop

    This is a regular, non-ES6, forward moving for loop which takes anywhere between 0.04 to 0.05 ms.

Lodash _.ForEach

    This is the lodash version of the for loop (_.ForEach) takes anywhere between 0.18 to 0.21 ms.

    Now comes the ES6 for loops. I did a forward iterating and a reverse for loop too and I noticed dramatic improvements in performance.

Forward iterating ES6 for loop

    This is a regular for loop using ES6 syntax which included 'let' instead of 'var' for variable declaration. The performance improvements here were just amazing. It took about 0.035 to 0.06ms to execute this for loop.

Reverse iterating ES6 For Loop

    As compared to the previous one, I just revered the for loop iteration in this case and the results were extremely good. This for loop took anywhere between 0.004 to 0.009 ms. This is an amazing improvement over any other loop.

    I will tabularize the results so that we can compare it better.

Foor Loop TypeTime taken (ms)
Non-ES6 For Loop0.04 - 0.05
Lodash _.ForEach0.18 - 0.21
ES6 Forward Iterating For Loop0.035 - 0.06
ES6 Reverse Iterating For Loop0.004 - 0.009

    Form all the tests that I have executed, I believe the reverse looping ES6 for loop is the fastest and is not just fast, it is like the Usain Bolt of For Loops. Do you guys have the same observations or do your tests vary from mine? Which for loop do you prefer? Any faster replacement for the for loop itself?

    Let me know your thoughts in the comments below. Until next time!

Popular posts from this blog

Where does Google get it's live traffic data from?

jQuery Mobile's Next Big Step

Geodesic Polyline