Reputation: 311
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;
}
selectionSort
vs. selectionSortWorse
Upvotes: 0
Views: 95
Reputation: 19445
When accessing an array element, for example result[pos]
, there is an overhead compared to accessing a direct variable, for example value
, at least 2 more things have to happen:
pos >= 0 && pos < result.length
Upvotes: 2