Java for loop vs. while loop. Performance difference?

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.

Leave a Comment