There are many types of for
loops for an array - which should you use? How will you balance performance vs. code readability? Is that even a valid question? Let’s see a few cases.
We will be seeing these distinct for
loops today -
for
for
-in
forEach
Note that the performance can be safely ignored for one off loops that do not hold up the user. If you are having an array of 15 elements and loop through it to display records on UI, it is not likely for you to even observe the difference in milliseconds.
You may want to chose the best option out there for a more complex loop. But remember - your DB or file operations may be holding you up and it is almost never the loop itself, and you should be considering parallel async operations for a really high no. of iterations.
That said, let’s get into the pseudo problem at hand.
We will use performance
statement to measure performance - apt, don’t you think? The basic structure will be -
|
|
There are of course better ways of controlling the results, but I am interested in fast results that I can verify myself, without breaking a sweat. We will fill the array with a single character ‘y’ - because, why not. Then, we measure looping through 10,00,000 elements of an array without doing any operations other than accessing the specific array element.
We will do three iterations of each test.
First the simple for
loop.
|
|
Next, for
-in
-
|
|
Yes, you are seeing the numbers right.
Finally, for
-each
-
|
|
To put the above three in perspective -
for | for-in | forEach |
---|---|---|
0.096500 0.147499 0.163900 |
212.619000 244.205399 234.532499 |
17.611999 20.537400 25.448599 |
I so much wanted to believe that the forEach
was wasting resources due to function calls but was obviously wrong. Although this does not drastically alter what I code (I mostly use for
loops - thanks to my muscle memory), but it is interesting to know what and why of things being introduced anew.
There is no point to this exercise other than telling y’all that
for
-in
is evil- and, newer is not necessarily better - choose the right tool for the job.
Also, no for
loop performance is really complete without while
.
|
|