Loops are language constructs. You can write a while
loop to do the same thing as a for
loop and vice versa.
Say an if statement has a relative cost of 1, what's the relative cost of for and while loops?
for
loops and while
loops also check a condition. In that sense, they also have a cost of 1
. The point is that there is typically something in the loop that will affect that condition.
Consider this code
public static void main(String[] args) throws Exception {
for (int i = 0; i < 10; i++) {
}
System.out.println("");
int i = 0;
while (i < 10) {
i++;
}
}
The bytecode generated is
// start for
0: iconst_0
1: istore_1
2: iload_1
3: bipush 10
5: if_icmpge 14
8: iinc 1, 1
11: goto 2
// end for
14: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream;
17: ldc #3 // String
19: invokevirtual #4 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
// start while
22: iconst_0
23: istore_1
24: iload_1
25: bipush 10
27: if_icmpge 36
30: iinc 1, 1
33: goto 24
36: return
// end while
You'll notice both loops do the exact same thing and generate the exact same bytecode.