DEV Community

Discussion on: Why is using javascript “for loop” for array iteration a bad idea?

Collapse
 
_prosen profile image
Prosen Ghosh • Edited

Surly Jon, for...loop is on of the fastest looping mechanism. In the example we are using forEach() for the exceptional behavior. Under the hood forEach() using something like the below code.

while(k < len){ // HERE len IS THE ACTUAL ARRAY LENGTH AND k START FROM 0
if(CHECK IF array[k] IS EMPTY SLOT)continue;
// DO THE OTHER STAFF
}
Enter fullscreen mode Exit fullscreen mode

Using forEach() can skip some unnecessary heavy calculation. What if we accidentally set array[400] = "SOME VALUE" and the other slots are empty, then we have to unnecessarily execute our heavy calculation function 400 times that will affect the performance.

Collapse
 
jonrandy profile image
Jon Randy 🎖️

If you're accidentally setting array[400] then that is your problem, and it needs fixing. The heavy calculation is merely a side effect of your bug

Thread Thread
 
_prosen profile image
Prosen Ghosh • Edited

yes, that is the point of my post how we can write good quality code, where can we do the mitake? if we do mistake in our code it can be affect the performance and create unnecessary bug.

Thread Thread
 
jasoncubic profile image
JasonCubic

It's still a micro optimization. The for loop can loop through 400 empty places in an array in what, 5ms? It's extremely fast.

Thread Thread
 
jonrandy profile image
Jon Randy 🎖️

Precisely - and by addressing the symptom rather than the cause i.e. by switching from a 'for loop' to forEach - you would actually be making the performance of the optimal (bug fixed) system worse than before.