DEV Community

Discussion on: Avoid slow Javascript code

Collapse
 
lexlohr profile image
Alex Lohr

Accessing the length outside the loop can sometimes make it easier to read for the developer, but also just like that you have implemented a faster loop iterator.

Loops are already heavily optimized in most JS interpreters. Unless the length could change inside the loop, the length will be cached by the engine.

If you don't need to break or return from inside the loop, consider using array methods like forEach, reduce or map, which too are already optimized and can improve readability in some cases.

Collapse
 
lexlohr profile image
Alex Lohr

That being said, never forget the golden rule of performance: avoid premature optimization. And also the corollary: performance is more often an issue than you think.

Developers usually have strong PCs, unlike most of our user base, so negligible bottle necks for us may be the reason for them to dislike our product for being slow or draining their device's battery.