Why is iterating through an array backwards faster than forwards

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

    I am not entirely sure about this, but here is my guess:

    For the following code:

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

    During runtime, there is an arr.length calculation after each loop pass. This may be a trivial operation when it stands alone, but may have an impact when it comes to multiple/huge arrays. Can you try the following:

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

    In the above code, we compute the array length just once, and operate with that computed number, rather than performing the length computation over and over again.

    Again, just putting my thoughts out here. Interesting observation indeed!

提交回复
热议问题