Why is iterating through an array backwards faster than forwards

后端 未结 7 1858
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 23:57

Given this code:

var arr = [];

for (var i = 0; i < 10000; ++i)
    arr.push(1);

Forwards

for (var i =          


        
7条回答
  •  独厮守ぢ
    2020-11-29 00:48

    Because your forwards-condition has to receive the length property of your array each time, whilst the other condition only has to check for "greater then zero", a very fast task.

    When your array length doesn't change during the loop, and you really look at ns-perfomance, you can use

    for (var i=0, l=arr.length; i

    BTW: Instead of for (var i = arr.length; i > 0; --i) you might use for (var i = arr.length; i-- > 0; ) which really runs through your array from n-1 to 0, not from n to 1.

提交回复
热议问题