34

Assume i have the following code, there are three for loop to do something. Would it run fast if i change the most outer for loop to while loop? thanks~~

int length = 200;
int test = 0;
int[] input = new int[10];

for(int i = 1; i <= length; i++) {
    for (int j = 0; j <=length - i; j++) {
        for (int k = 0; k < length - 1; k++) {
            test = test + input[j + k];
        }
    }
}
jjnguy
  • 136,852
  • 53
  • 295
  • 323

15 Answers15

65

No, changing the type of loop wouldn't matter.

The only thing that can make it faster would be to have less nesting of loops, and looping over less values.

The only difference between a for loop and a while loop is the syntax for defining them. There is no performance difference at all.

int i = 0;
while (i < 20){
    // do stuff
    i++;
}

Is the same as:

for (int i = 0; i < 20; i++){
    // do Stuff
}

(Actually the for-loop is a little better because the i will be out of scope after the loop while the i will stick around in the while loop case.)

A for loop is just a syntactically prettier way of looping.

jjnguy
  • 136,852
  • 53
  • 295
  • 323
  • 5
    you can add scope around the i to knock it off the stack once you are done with it :D – DigitalZebra Jul 24 '09 at 14:01
  • 2
    A for-loop and a while-loop is actually slightly different due to how continue behaves. The incrementation will always occur in the for-loop whereas a continue in the while-loop would skip it, causing the loop to go on forever. – cleong Nov 26 '12 at 09:21
  • 1
    Why isn't this the correct answer? IMHO this explains exactly how to work with those loops. – D4ddy Oct 29 '15 at 11:00
35

This kind of micro-optimization is pointless.

  • A while-loop won’t be faster.
  • The loop structure is not your bottleneck.
  • Optimize your algorithm first.
  • Better yet, don’t optimize first. Only optimize after you have found out that you really have a bottleneck in your algorithm that is not I/O-dependant.
Bombe
  • 81,643
  • 20
  • 123
  • 127
12

Someone suggested to test while vs for loops, so I created some code to test whether while loops or for loops were faster; on average, over 100,000 tests, while loop was faster ~95% of the time. I may have coded it incorrectly, I'm quite new to coding, also considering if I only ran 10,000 loops they ended up being quite even in run duration.

edit I didn't shift all the array values when I went to test for more trials. Fixed it so that it's easier to change how many trials you run.

import java.util.Arrays;

class WhilevsForLoops {

 public static void main(String[] args) {

final int trials = 100; //change number of trials
final int trialsrun = trials - 1;

boolean[] fscount = new boolean[trials]; //faster / slower boolean
int p = 0; // while counter variable for for/while timers



while (p <= trialsrun) {
     long[] forloop = new long[trials];
     long[] whileloop = new long[trials];

     long systimeaverage; 
     long systimenow = System.nanoTime();
     long systimethen = System.nanoTime();

     System.out.println("For loop time array : ");
     for (int counter=0;counter <= trialsrun; counter++) {
         systimenow = System.nanoTime();
         System.out.print(" #" + counter + " @");
         systimethen = System.nanoTime();
         systimeaverage = (systimethen - systimenow);
         System.out.print( systimeaverage + "ns |");

         forloop[counter] = systimeaverage; 
     }

     int count = 0;
     System.out.println(" ");
     System.out.println("While loop time array: ");
     while (count <= trialsrun) {
         systimenow = System.nanoTime();
         System.out.print(" #" + count + " @");
         systimethen = System.nanoTime();
         systimeaverage = (systimethen - systimenow);
         System.out.print( systimeaverage + "ns |");

         whileloop[count] = systimeaverage;
         count++;
     }


     System.out.println("===============================================");
     int sum = 0;

     for (int i = 0; i <= trialsrun; i++) {
        sum += forloop[i];
     }

     System.out.println("for loop time average: " + (sum / trials) + "ns");

     int sum1 = 0;

     for (int i = 0; i <= trialsrun; i++) {
         sum1 += whileloop[i];
     }
     System.out.println("while loop time average: " + (sum1 / trials) + "ns");



     int longer = 0;
     int shorter = 0;
     int gap = 0;

     sum = sum / trials;
     sum1 = sum1 / trials; 

     if (sum1 > sum) {
        longer = sum1;
        shorter = sum;
     }
     else {
        longer = sum;
        shorter = sum1;
     }

     String longa;

     if (sum1 > sum) {
        longa = "~while loop~";
     }
     else {
         longa = "~for loop~";
     }

     gap = longer - shorter; 
     System.out.println("The " + longa + " is the slower loop by: " + gap + "ns");
     if (sum1 > sum) {
     fscount[p] = true; }
     else {
         fscount[p] = false;
     }
     p++;
}

    int forloopfc=0;
    int whileloopfc=0;

    System.out.println(Arrays.toString(fscount));

    for(int k=0; k <= trialsrun; k++) {
        if (fscount[k] == true) {
            forloopfc++; }
            else {
                whileloopfc++;}

    }

    System.out.println("--------------------------------------------------");

    System.out.println("The FOR loop was faster: " + forloopfc + " times.");
    System.out.println("The WHILE loop was faster: " + whileloopfc + " times.");
 }

}
Sleepy
  • 129
  • 1
  • 3
10

you cant optimize it by changing it to while.

you can just increment speed very very very very little by changing the line

for (int k = 0; k < length - 1; k++) {

by

for (int k = 0; k < lengthMinusOne; k++) {

where lengthMinusOne is calculated before

this subtraction is just calculating almost (200x201/2) x (200-1) times and it is very little number for computer :)

ufukgun
  • 6,889
  • 8
  • 33
  • 55
  • 7
    The Java compiler will optimize that call out usually these days. But you are technically correct about that being faster. – jjnguy Jul 22 '09 at 14:08
  • 4
    Heh, I was half expecting someone to suggest changing `k++` to `++k` :D – Mike Caron Jul 28 '10 at 15:05
  • you will save very very very very little time of compiling. Most compilers now support such optimizations check https://stackoverflow.com/questions/5981460/optimization-by-java-compiler – Amit Kumar May 04 '18 at 13:07
4

here's a helpful link to an article on the matter

according to it, the While and For are almost twice as faster but both are the same.

BUT this article was written in 2009 and so i tried it on my machine and here are the results:

  • using java 1.7: the Iterator was about 20%-30% faster than For and While (which were still the same)
  • using java 1.6: the Iterator was about 5% faster than For and While (which were still the same)

so i guess the best thing is to just time it on your own version and machine and conclude from that

levtatarov
  • 1,632
  • 6
  • 24
  • 36
  • In any safe language, the use of an iterator is usually faster, since the interpretor/compiler can omit bound-checking. – cleong Nov 26 '12 at 08:57
2

Even if the hypothesis of the while loop being faster than the for loop were true (and it's not), the loops you'd had to change/optimize wouldn't be the outer ones but the inner ones, because those are executed more times.

fortran
  • 74,053
  • 25
  • 135
  • 175
2

The difference between for and while is semantic :

  • In a while loop, you will loop as long as the condition is true, which can vary a lot, because you might, in your loop, modify variables using in evluating the while condition.
  • Usually, in a for loop, you loop N time. This N can be variable, but doesn't move until the end of your N loop, as usually developpers doesn't modify variables evaluated in the loop condition.

It is a way to help other to understand your code. You are not obliged not to modify for loop variables, but it is a common (and good) practice.

Clement Herreman
  • 10,274
  • 4
  • 35
  • 57
1

No, you're still looping the exact same number of times. Wouldn't matter at all.

aquinas
  • 23,318
  • 5
  • 58
  • 81
1

Look at your algorithm! Do you know beforehand which values from your array are added more than one time?

If you know that you could reduce the number of loops and that would result in better performance.

Roalt
  • 8,330
  • 7
  • 41
  • 53
1

There would be no performance difference. Try it out!

The JVM and further, the compiler, would make both loops into something like

    label:
       ;code inside your for loop.
    LOOP label
Adrian
  • 5,603
  • 8
  • 53
  • 85
0

It would only matter if you are using multi-thread or multiple processor programming. Then it would also depends on how you assign the loops to the various processors/threads.

Extrakun
  • 19,057
  • 21
  • 82
  • 129
0

No, it's not going to make a big difference, the only thing is that if your nesting loops you might want to consider switching up for example for organizational purposes, you may want to use while loop in the outer and have for statements inside it. This wouldn't affect the performance but it would just make your code look cleaner/organized

0

You can calculate it yourself.

int length = 200;
int test = 0;
int[] input = new int[10];

long startTime = new Date().getTime();

for(int i = 1; i <= length; i++) {
    for (int j = 0; j <=length - i; j++) {
        for (int k = 0; k < length - 1; k++) {
            test = test + input[j + k];
        }
    }
}

long endTime = new Date().getTime();
long difference = endTime - startTime;
System.out.println("For - Elapsed time in milliseconds: " + difference);


test = 0;
input = new int[10];

int i = 0, j = 0, k = 0;

startTime = new Date().getTime();

while(i < length) {
    while(j <= length - i ) {
        while(k < length - 1) {
            test = test + input[j + k];
            k++;
        }
        j++;
    }
    i++;
}

endTime = new Date().getTime();
difference = endTime - startTime;
System.out.println("While - Elapsed time in milliseconds: " + difference);
Serdar Polat
  • 3,992
  • 2
  • 12
  • 12
0

The for loop and while loop both are iteration statements, but both have their distinct feature.

Syntax

While Loop

//setup counter variable
int counter = 0;

while ( condition) {

    //instructions 

    //update counter variable
    counter++;  //--> counter = counter + 1;

}

For Loop

for (initialization; condition; iteration){
    //body of for loop
}

The for loop does have all its declaration (initialization, condition, iteration) at the top of the body of the loop. Adversely, in a while loop only initialization and condition are at the top of the body of the loop and iteration may be written anywhere in the body of the loop.

Key Differences Between for and while loop

  1. In the for loop, initialization, condition checking, and increment or decrement of iteration variable are done explicitly in the syntax of a loop only. As against, in the While loop, we can only initialize and check conditions in the syntax of the loop.

  2. When we are aware of the number of iterations that have to occur in the execution of a loop, then we use for loop. On the other hand, if we are not aware of the number of iteration that has to occur in a loop, then we use a while loop.

  3. If you fail to put the condition statement in the for loop, it will lead to an infinite iteration of a loop. In contrast, if you fail to put a condition statement in the while loop it will lead to a compilation error.

  4. The initialization statement in the syntax of the for loop executes only once at the start of the loop. Conversely, if the while loop is carrying an initialization statement in its syntax, then the initialization statement in the while loop will execute each time the loop iterates.

  5. The iteration statement in the for loop will execute after the body for loop executes. On the contrary, the iteration statement can be written anywhere in the body of the while loop so, there can be some statements that execute after the execution of the iteration statement in the body of the `while loop.

snishalaka
  • 1,738
  • 1
  • 9
  • 17
-2

Based on this: https://jsperf.com/loops-analyze (not created by me) the while loop is 22% slower than a for loop in general. At least in Javascript it is.

Arash R
  • 33
  • 7