Manuel
Manuel

Reputation: 311

Why is so much worse to call a place of an array than a variable

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

Upvotes: 0

Views: 95

Answers (1)

Roee Gavirel
Roee Gavirel

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:

  • Verifying range, for the example, verifying that pos >= 0 && pos < result.length
  • The address of the element needs to be calculated, something like "result address + (pos * element_size)" instead of just "value address". This shouldn't be significant, but if repeated enough might have an impact.

Upvotes: 2

Related Questions