Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript simple for loop versus for...of performances

I have seen that since ECMA 6 we can use for...of instead of the traditionnal for loop:

for( let i = 0 ; i < arr.length ; i++ ) {
    var elm = arr[i];
    // do stuff
}

VS

for( let elm of arr ) {
    // do stuff
}

Has you see the second one is lot more readable, simple and maintainable!

I just wonder how performant the second syntax is as I need to use it a lot in a render loop (60 times per seconds) for a game.

Have you got a clue ?

like image 969
TOPKAT Avatar asked Mar 08 '23 08:03

TOPKAT


2 Answers

The first one (the standard for-loop) performs much better according to this test.

like image 157
Eren Tantekin Avatar answered Mar 10 '23 22:03

Eren Tantekin


Newer language features often don't perform as well at first because they haven't been given as much attention for optimization.

The more people use them, the more likely they'll get attention, so overall, use whichever one provides better, clearer code unless you have an extreme situation where performance is crucial.

like image 35
spanky Avatar answered Mar 10 '23 21:03

spanky