array.forEach running faster than native iteration? How?

前端 未结 5 856
隐瞒了意图╮
隐瞒了意图╮ 2021-02-08 19:38

http://jsperf.com/testing-foreach-vs-for-loop

It was my understanding that Test Case 2 should run more slowly than Test Case 1 -- I wanted to see how much more slowly. I

5条回答
  •  一向
    一向 (楼主)
    2021-02-08 20:35

    There are many iteration optimizations that your for loop is missing such as:

    • cache the array length
    • iterate backwards
    • use ++counter instead of counter++

    These are the ones that I have heard of and used, I am sure there are more. If memory serves me correct, the backwards iterating while loop is the fastest of all looping structures (in most browsers).

    See this jsperf for some examples.

    Edit: links for postfix vs prefix perf test and iterating backwards. I was not able to find my reference for using +=1 instead of ++, so I have removed it from the list.

提交回复
热议问题