0

When writing loops like the ones below, is it best to use the value used to initialise the size of an array:

int n = foo();
int[] arr = new int[n];

for (int i = 0; i < n; i++) {
    ...
}

or use the length property on the array:

int n = foo();
int[] arr = new int[n];

for (int i = 0; i < arr.length; i++) {
    ...
}

Is it a matter of preference, or is there an advantage to one of them?

user1081679
  • 307
  • 1
  • 2
  • 15
  • 4
    A matter of preference. Using `n` avoid dereferencing an object instance. But that's trivial. – Elliott Frisch Apr 27 '19 at 19:25
  • 1
    Just a guess, but I suspect that JIT (Just In Time optimizer) will start working it will replace `arr.length` with its value (which is also stored in `n`) so there shouldn't be any difference after that. – Pshemo Apr 27 '19 at 19:29
  • Also consider `for (int value : arr)`. Regarding micro-optimisation (using n to avoid de-reference): don’t trust your intuition on what is easy for JIT to optimise. – Lesiak Apr 27 '19 at 19:31
  • 2
    @Pshemo is right here, JIT would optimize this right away. You can read more on the cost of calling `length` on array here :https://stackoverflow.com/questions/1208320/what-is-the-cost-of-calling-array-length – Dominik Wosiński Apr 27 '19 at 19:34
  • If you use arr.length, you will always be correct. If you change n or use a different variable, then you may need to update your code in different spots. On the other hand, if you use a static variable like `final static int MAX_ARGS = 10` that adds to the documentation of your code. – WJS Apr 27 '19 at 22:14

1 Answers1

0

it works both ways, but i think it's better to use .length because you don't need to add a variable that will be useless and take some memory.

hewa jalal
  • 952
  • 11
  • 24
  • Actually you would (should) use a different variable at least to initialize the array. `int[n]` is preferred over `int[10]` say. Don't use magic numbers because they make code hard to upgrade and don't describe what is going on. And `n` is also a variable, just like `length` albeit intrinsically final. – WJS Apr 27 '19 at 22:17