Given the following (which I have taken from a larger program)
t1 = System.currentTimeMillis();
for (int i = 0; i < 3; i++) {
t2 = System.currentTimeMillis();
for (int j = i; j <= 1000; j += 3) {
t3 = System.currentTimeMillis();
//j loop body
}
}
When I run the program and test it for speed, I find that
t2 - t1 is around 2700 milliseconds
t3 - t2 is around 1300 milliseconds
In comparison, the following program prints a time of 3 milliseconds to the console
public class Sum {
public static void main(String[] args) {
int sum = 0;
long t1 = System.currentTimeMillis();
for (int k = 0; k < 1000000; k++) {
sum += k;
}
System.out.println(System.currentTimeMillis() - t1);
System.out.println(sum);
}
}
How can simply entering the i and j for loops take so much time?
I appreciate that I haven't shown the full program for the i and j loops, but if anyone knows of any reason why this might be happening, that would save me creating an appropriate sample program (that isn't too big) to post here.