lets look at the following two java methods:
static void performance1() {
int a=0;
int b=0;
int[] arrayA = { 3, 4, 5 };
int[] arrayB = { 4, 5, 6, 3, 4, 5, 6, 7, 8, 4 };
long start = System.currentTimeMillis();
for (int i = 0; i < 100000000; i++) {
for (int k = 0; k < 100; k++) {
a = arrayA[2];
b = arrayB[1];
}
}
long end = System.currentTimeMillis();
System.out.println(end - start);
}
static void performance2() {
int a=0;
int b=0;
int[] arrayA = { 3, 4, 5 };
int[] arrayB = { 4, 5, 6, 3, 4, 5, 6, 7, 8, 4 };
long start = System.currentTimeMillis();
for (int i = 0; i < 100000000; i++) {
for (int k = 0; k < 100; k++) {
b = arrayB[arrayA[2]];
}
}
long end = System.currentTimeMillis();
System.out.println(end - start);
}
The first method takes 209 ms to execute on my system, the seccond 4295! so 20 times as much. How can this be? As far as i can see this i can get a 20time performance increase if i declare 3 seperate variables instead of arrayA, because the following method executes very fast again:
static void performance3() {
int a=0;
int b=0;
int[] arrayA = { 3, 4, 5 };
int[] arrayB = { 4, 5, 6, 3, 4, 5, 6, 7, 8, 4 };
long start = System.currentTimeMillis();
for (int i = 0; i < 100000000; i++) {
for (int k = 0; k < 100; k++) {
b = arrayB[a];
}
}
long end = System.currentTimeMillis();
System.out.println(end - start);
}
Am i overlooking something obvious here? it really seems suprising to me that the difference is so huge. Thank you anyways for explanations:)
arrayBas it doesn't know the index at compile time (since it could change at runtime).arrayB[a]is alwaysarrayB[0]?