Why is iterating through an array backwards faster than forwards

后端 未结 7 1864
佛祖请我去吃肉
佛祖请我去吃肉 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:55

    i > 0 is faster than i < arr.length and is occurring on each iteration of the loop.

    You can mitigate the difference with this:

    for (var i = 0, len = arr.length; i < len; ++i) {;
    }
    

    This is still not as fast as the backwards item, but faster than your forward option.

提交回复
热议问题