I'm starting with Java, and I just came up with this huge difference: why is making references to an array so much worse than assigning the value to a variable and then calling the variable? (If that's not the problem of my code, then what's the problem of my code?)
I tried to implement selection sort in Java and here I show you the times.
In my mind an array was like a list of symbolic variables so I don't see how is that much worse to call array items directly.
Here's the code (times below)
public static int[] selectionSort(int ... numbers) {
int pos, value;
int[] result = numbers.clone();
for (int i = 0; i < result.length - 1; i++) {
value = result[i];
pos = i;
for (int j = i + 1; j < result.length; j++) {
if (result[j] < value) {
value = result[j];
pos = j;
}
}
result[pos] = result[i];
result[i] = value;
}
return result;
}
public static int[] selectionSortWorse(int ... numbers) {
int pos, value;
int[] result = numbers.clone();
for (int i = 0; i < result.length - 1; i++) {
pos = i;
for (int j = i + 1; j < result.length; j++) {
if (result[j] < result[pos]) {
pos = j;
}
}
value = result[pos];
result[pos] = result[i];
result[i] = value;
}
return result;
}
Time comparison (average of 10) of selectionSort
vs. selectionSortWorse
- length of array: 10000; times 33.14 ms vs. 52.33 ms
- length of array: 20000; times 127.13 ms vs. 207.46 ms
- length of array: 50000; times 793.56 ms vs. 1302.48 ms
- length of array: 100000; times 3096.43 ms vs. 5072.56 ms