KKLong
KKLong

Reputation:

Java for loop vs. while loop. Performance difference?

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];
        }
    }
}

Upvotes: 35

Views: 97869

Answers (15)

snishalaka
snishalaka

Reputation: 1913

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.

Upvotes: 0

Serdar Polat
Serdar Polat

Reputation: 4390

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);

Upvotes: 0

user12929063
user12929063

Reputation:

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

Upvotes: 0

Arash R
Arash R

Reputation: 33

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.

Upvotes: -2

Sleepy
Sleepy

Reputation: 129

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.");
 }

}

Upvotes: 12

levtatarov
levtatarov

Reputation: 1712

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

Upvotes: 4

Adrian
Adrian

Reputation: 5681

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

Upvotes: 1

Clement Herreman
Clement Herreman

Reputation: 10536

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.

Upvotes: 2

jjnguy
jjnguy

Reputation: 138864

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.

Upvotes: 65

fortran
fortran

Reputation: 76057

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.

Upvotes: 2

Bombe
Bombe

Reputation: 83845

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.

Upvotes: 35

ufukgun
ufukgun

Reputation: 7209

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 :)

Upvotes: 10

Roalt
Roalt

Reputation: 8440

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.

Upvotes: 1

Extrakun
Extrakun

Reputation: 19305

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.

Upvotes: 0

aquinas
aquinas

Reputation: 23786

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

Upvotes: 1

Related Questions