问题
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 ?
回答1:
The first one (the standard for-loop) performs much better according to this test.
回答2:
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.
回答3:
generally speaking, for..of
will be slower than for(;;)
, looping an Array. Because it deals with Iterators/Generators, and that involves some overhead in contrast to incrementing a variable and comparing it against some other value.
BUT, and as you can see it is a big but
Don't prematurely optimize code. Write the code, check where your actual bottlenecks are and start optimizing these.
Due to code optimization, microbenchmarks are useless. They test the performance of the actual test itself; not the techniques you're trying to benchamark. The performance may change by multiple orders of magnitude in any direction when applying the techniques in your actual production code. And that means actually every single occurance. at one place a
for(;;)
loop may be faster, somewhere elsefor..of
may be better siuted.
During my time in AS3 I've learned that function calls are expensive the key to optimizing code is inlining. In JS I regularly see Array#forEach
outrun a manual loop when JS can optimize the sh*t out of the function executed on the Array + can determine that it can get rid of all the safety features (that have to be executed behind the scenes), since this code won't be called with an sparse Array or somehow else access an undefined key on that Array.
Summary:
Unless you debug your actual code in its actual context you have no clue how it will actually be optimized; you can only estimate or guess.
And in JS, the internal optimizer is the key to really fast code. Not some micro optimizations you apply to your code.
来源:https://stackoverflow.com/questions/45651111/javascript-simple-for-loop-versus-for-of-performances