I was curious if I declare the variable outside of the loop, it should run faster, because when I declare it inside the loop, then in every loop the system needs to allocate a new integer in the memory which takes time. I ran the test, and the runtimes are: Outside: 3600ms Inside: 1300ms
It is the exact opposite, what I expected. Why is it faster when I declare it inside ?
public class DeclarationTestLoop {
static double outer = 9500000;
static double inner = 100;
static void outside() {
long start = System.currentTimeMillis();
Integer value = 1;
for(double i=0; i<outer; i++) {
for(int k=0; k<inner; k++) {
value++;
value--;
}
}
long end = System.currentTimeMillis();
System.out.println(end-start);
}
static void inside() {
long start = System.currentTimeMillis();
for(double i=0; i<outer; i++) {
for(int k=0; k<inner; k++) {
Integer value = 1;
value++;
value--;
}
}
long end = System.currentTimeMillis();
System.out.println(end-start);
}
public static void main(String[] args) {
System.out.println("outside");
outside();
outside();
outside();
outside();
outside();
outside();
outside();
outside();
outside();
outside();
outside();
outside();
System.out.println("inside");
inside();
inside();
inside();
inside();
inside();
inside();
inside();
inside();
inside();
inside();
inside();
inside();
System.out.println("toggle");
outside();
inside();
outside();
inside();
outside();
inside();
outside();
inside();
outside();
inside();
}
}