I have this code in Java, using two different types of loops.
public class Test {
public static void main(String[] args){
long fl = 0, wl = 0;
int i = 0;
int a = 0;
long start = 0, stop = 0;
start = System.currentTimeMillis();
while(i<2000000000){
if(i%2 == 0)
a++;
else
a--;
i++;
}
stop = System.currentTimeMillis();
wl = stop-start/2;
System.out.println("\nWhile loop = "+wl);
i = 0;
a = 0;
start = 0;
stop = 0;
start = System.currentTimeMillis();
for(;i<2000000000;){
if(i%2 == 0)
a++;
else
a--;
i++;
}
stop = System.currentTimeMillis();
fl = stop-start/2;
System.out.println("For loop = "+fl);
System.out.println("Difference = "+(fl-wl));
}
}
Now, after running the program multiple times, I have come to the conclusion that the second loop is always executing slower than the first loop. At first, I thought it had something to do with one being a for loop and the other being a while loop, but even when I reversed the order, the second loop still executes slower. Here is the output of a sample run.
While loop = 688721817947
For loop = 688721824295
Difference = 6348
Now, why is this happening.
0.000001%
?