0

What is faster:

int[] nums = [1, 4, 8, 2, etc...];

//access length each time?
for (int i : nums) {
   i = nums.length * i;
}

OR...

int[] nums = [1, 4, 8, 2, etc...];

//store length off?
int length = nums.length;
for (int i : nums) {
   i *= length;
}

Storing the length takes up space, but if you have to determine the length N times, that could slow it down. I'm wondering if nums.length is effectively stored off when the int[] is created, or if its dynamically determined each time referenced.

Mugunga
  • 45
  • 4
  • 5
    The length doesn't need to be recomputed, since it's internally stored in the array header (which is an implementation detail that you can't see often). With that being said, unless you are actually encountering a slowdown that affects the users of your program, it's **far** better to write clean, idiomatic, readable code, than to try to optimize for every bit of performance. – nanofarad May 25 '20 at 21:45
  • 3
    The JVM is usually clever enough to generate optimized code out of this. To perform multiplications, the value must be pushed on the stack the same way if it were a normal variable. Btw, if the field access was a performance problem, then using enhanced-for-loops would probably be more expensive, and a counting loop would be preferable (doesn't use iteraters. then again, the JVM often optimizes simple iterator-loops anyway). To perform micro-benchmarks, tools such as JMH can be used. In summary: it probably doesn't matter, unless you have already identified this loop to be a bottleneck. – knittl May 25 '20 at 21:50
  • 2
    Neither example makes any sense. Why multiply `i` by anything if it immediately leaves scope and you don't use it for anything? – Elliott Frisch May 25 '20 at 21:51
  • Check https://stackoverflow.com/questions/27933915/in-for-loops-does-the-length-of-the-array-get-evaluated-each-iteration – Arvind Kumar Avinash May 25 '20 at 22:06
  • Also https://stackoverflow.com/questions/1208320/what-is-the-cost-of-calling-array-length – Arvind Kumar Avinash May 25 '20 at 22:08
  • 1
    Clean and readable code is absolutely primary. Micro-optimizations are often premature. – MC Emperor May 25 '20 at 22:14
  • As Elliot Frisch said, setting `i` to anything is useless. You should probably use a traditional for loop anyways. – user May 25 '20 at 22:36
  • 1
    nums.length is effectively an int already, so you're not saving any processing time. However, if the length() or size() method takes a long time to execute, then saving the result in an int after one execution makes sense. – Gilbert Le Blanc May 26 '20 at 00:25

0 Answers0