Recently, Kent C. Dodds posted about an instance where using a for loop dramatically resulted in better performance.
When you delve into how
reduce methods work (based on callbacks), really it is of no surprise to anyone who sees the results for themselves that these methods are a lot slower.
Replying to Kent's Tweet, I mentioned how I always use for loops and how their performance is unrivalled:
Really, it did not take long for the defensive Tweets from other devs on Twitter.
Yes, for loops are faster and yes, if you're not careful they can have unintended side effects as a result of not using better-suited methods like
reduce, but I don't use for loops with the sole purpose of optimising my code.
In most cases, you won't notice any difference in performance for small data sets. When you're dealing with tens of thousands of items like Kent was, then you definitely will.
If you are working with promises and want to use
async/await then you need to use a for loop to do that as those beloved one-liner methods do not support them very well.
If you want to be able to control the flow of the loop (break out of it), then you will want to use a for loop.
While for loops will add to the size of your code and not be as "clean", we need to stop focusing on clean code and focusing on clear code. To me, nothing is more immediately clear than a for loop.
I am also not advocating against using those specific methods. I still use
reduce where applicable. In most instances, I find for loop is easier to write, even if it usually results in more code.