I run this code and get run time for both loop blocks. the interesting thing is that when I set the upper bound for j 2 the run time for each block is ~3500ms but when I run it with upper bound for j 10, the run time is <10ms. fast code:
long start = System.currentTimeMillis();
int a = 10;
for (int i = 0; i < Integer.MAX_VALUE; i++) {
for (int j = 0; j < 10; j++) {
for (int k = 0; k < 1; k++) {
a += 2;
}
}
}
long finish = System.currentTimeMillis();
System.out.println(finish - start);
start = System.currentTimeMillis();
a = 10;
for (int i = 0; i < Integer.MAX_VALUE; i++) {
for (int j = 0; j < 10; j++) {
for (int k = 0; k < 1; k++) {
a = a + 2;
}
}
}
finish = System.currentTimeMillis();
System.out.println(finish - start);
slow code:
long start = System.currentTimeMillis();
int a = 10;
for (int i = 0; i < Integer.MAX_VALUE; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 1; k++) {
a += 2;
}
}
}
long finish = System.currentTimeMillis();
System.out.println(finish - start);
start = System.currentTimeMillis();
a = 10;
for (int i = 0; i < Integer.MAX_VALUE; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 1; k++) {
a = a + 2;
}
}
}
finish = System.currentTimeMillis();
System.out.println(finish - start);
Why 10 runs faster than 2?!