We have come to appreciate the performance and readability of the ol’ for loop. But, just how much should we be appreciating the performance?
We already did a huge scientific study on different avatars of for
. This is the time that we do another highly ineffective test for different types of loops so that we can prove nothing to no one.
Consider this simple array.
|
|
We will measure the time taken to go through the array and print every element.
Simple for
|
|
‘Efficient’ for
A lot of smart guys recommend using a variable to store the array length value in a for
. This should potentially cut down the time to lookup whether the array should end.
|
|
More modern runtime engines would have probably optimized this already. I did not find any difference while running Node 12.
while
loop
From my previous experience with while
, I did not expect to see much difference.
|
|
do-while
loop
It will be crazy to expect anything less with a do
-while
when we already had while
.
|
|
Results
Simple for |
Efficient for |
while |
do-while |
---|---|---|---|
359.868ms 344.918ms 410.166ms |
383.720ms 378.136ms 470.718ms |
390.582ms 311.583ms 429.276ms |
372.058ms 341.528ms 455.252ms |
Since we started with the rock-bottom expectation to not prove anything, we have achieved our stated objectives.
But, we did see the usage of console.time()
instead of the node-specific perf_hooks
to measure performance. So, it is that we easily exceeded 100% there.