Javascript simple for loop versus for…of performances

↘锁芯ラ 提交于 2020-02-28 07:54:47

问题


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

  1. Don't prematurely optimize code. Write the code, check where your actual bottlenecks are and start optimizing these.

  2. 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 else for..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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!