1

I was going through some JavaScript code when a loop structure caught my eye. It wasn't anything particularly special, rather it iterated in a manner different from what I do. When I need to loop something that isn't dependent on order, I typically count up, iterating from beginning to end, like so:

do
{
    // I feel like I'm going in circles
    i++;
} while (i < length)

However, this JavaScript function counted down, looping from end to beginning.

var i = data.length - 1;
if(i >= 0)
{                   
    do
    {
        // Around and around, we go                     
    }while(i--)
}

Is there any advantage to counting downward or is it just up to developer preference?

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
Jason L
  • 1,812
  • 2
  • 22
  • 43
  • On a sidenote, is there a way to keep "--" from turning into an em dash? – Jason L Jul 31 '12 at 15:31
  • Also take a look at [Duff's Device](http://en.wikipedia.org/wiki/Duff's_device) if you want to optimize even further. It reduces the number of comparisons you have to perform (most commonly by a factor of 8). – lbstr Jul 31 '12 at 15:38

5 Answers5

4

I you are removing things from the array, going backwards is better.

Consider you have an array of 10 things, and you end up wanting to remove items at indexes 3 and 4, thru some conditional that is executed during the loop. You are incrementing your counter. When you remove at 3, what happens to the array vis-a-vis the counter? The array length shrinks to 9, what was at index 4 is now at index 3, and you increment the counter to 4. You just skipped something you wanted to delete. If you go backwards, you avoid this issue.

Also, going backwards is faster, because processors can compare the index to 0 faster than they can compare the index to a random number.

Community
  • 1
  • 1
hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
  • Worse - if iterating a dynamic array collection and deleting some objects, counting up will result in overrunning the end of the array. Counting down will be OK. – Martin James Jul 31 '12 at 15:26
0

Probably not. Most likely the developer just wanted to count backwards.

However, standard 0 to length-1 loops aren't always ideal. For example, under specific caching architectures, it might, for whatever reason, be faster to access elements of a structure in reverse. I can't think of any reasonable cases where this would happen in JavaScript, but it does happen in application based languages, especially relatively low level ones like C.

Chris
  • 440
  • 3
  • 8
0

To quote a similar SO question/answer:

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.

Loop Iteration - Bergi

Community
  • 1
  • 1
Jamie Keeling
  • 9,806
  • 17
  • 65
  • 102
0

Hmmm. Theoretically no, there should be no difference between looping using for, or using while,but here are my 2 cents. The only way to see whether there's a difference is to do a performance test, one using while and another using for, lets say on 1 million element, calculate the execution time and see for yourself. There are many optimization techniques to loop (whether for or while), one of the most common is to do multiple iterations in one loop. example: a standard for loop is:

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

Now we optimize this by doing the same multiple time on each iteration

var i;
    for (i=0;i < N; i+=5) {
        if (i < N-5) {
          bla();
          bla();
          bla();
          bla();
          bla();
        }
    }
for (j=i; j <N;j++){
  bla();
}

This way guarantees less number of iterations. Depending on what you do each iteration, and the size of your array/stacks it could provide better performance. There are alot of articles around on how to improve the performance of loops

Moataz Elmasry
  • 2,509
  • 4
  • 27
  • 37
0

I saw at least one study that shows the decreasing while loop is the fastest way to do a loop in JavaScript: https://blogs.oracle.com/greimer/entry/best_way_to_code_a

Note this is specific to the JavaScript engines in the study and other languages/machine implementations may provide different results. In C for instance an optimizing compiler may unroll your loop completely and the generated code doesn't loop at all.

Dave Rager
  • 8,002
  • 3
  • 33
  • 52