Why is iterating through an array backwards faster than forwards

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

    If you want to have them at same pace, you can do that for forward iteration;

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

    So, your script won't need to take length of array on everystep.

    0 讨论(0)
  • 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<l; 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.

    0 讨论(0)
  • 2020-11-29 00:49

    do it like below, it will perform in same way. because arr.length takes time in each iteration in forward.

    int len = arr.length;
    

    forward

    for (var i = 0; i < len; ++i) {
    }
    

    backward

    for (var i = len; i > 0; --i) {
    }
    
    0 讨论(0)
  • 2020-11-29 00:51

    And these are equally good:

    var arr= [], L= 10000;
    while(L>-1) arr[L]= L--;
    

    OR

    var arr= [], i= 0;
    while(i<10001) arr[i]=i++;
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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!

    0 讨论(0)
提交回复
热议问题