I ran this segment of code: (outer loop runs 100 times, inner loop runs 1 billion times.)
long l = 0;
for(int i = 0; i < 100; i++)
for(int j = 0; j < 1000000000; j++)
l++;
System.out.println(l);
This took around 11-12 seconds when I ran it.
Then I ran this segment of code:
long l = 0;
int i = 0, j = 0;
for(; i < 100; i++)
for(; j < 1000000000; j++)
l++;
System.out.println(l);
and this took about 100 ms (0.1 seconds) whenever I ran it.
Does anyone have any idea why there's a big difference? My theory is that for every value of 'i', the inner for loop has to initialize j again, which gives it more operations to do, so it makes sense that it takes longer. However, the difference is huge (by about 100 times), and with other similar tests, the same thing doesn't happen.
If you want to see it yourself, this is how I timed it:
class Main {
static long start, end;
public static void main(String[] args) {
start();
long l = 0;
int i = 0, j = 0;
for(; i < 100; i++)
for(; j < 1000000000; j++)
l++;
System.out.println(l);
end();
print();
}
public static void start() {
start = System.currentTimeMillis();
}
public static void end() {
end = System.currentTimeMillis();
}
public static void print() {
System.out.println((end - start) + " ms.");
}
}