Alex Rivera | Logout

for loop optimization

Asked 2011-05-23T06:22:34.787
46
List<String> flowers = new ArrayList<String>();

My for loop currently looks like this...

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

OR should I change this to look like the code given below

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

Which is more performant (assuming I have a large array of flowers), I am guessing it should be the latter.

Edit
Report

2 Answers

11

The JVM can't optimize it because size() is a method, and JVM can't (and won't try to) determine that the size() will always return the same value in this context. Provided size() value doesn't change, the second one is slightly more performant, but the gain is so, so slight that you don't really have to even consider using it.

answered 2011-05-23T07:07:26.597
4

From the Java language specification (14.14.1):

The basic for statement executes some initialization code, then executes an Expression, a Statement, and some update code repeatedly until the value of the Expression is false.

The Expression is i < flowers.size() in your first example and it is evaluated once in every iteration. In your special case it shouldn't make a noteable difference, because flowers.getSize() on ArrayList is a very short method. But, in general, if the result of the expression is the same for each iteration and expensive, then do a pre calculation.

Consequence: this has to produce the same output in every implementation of a Java virtual machine and proves, that Expression is evaluate once in each iteration:

int counter2 = 10;
for (int counter1 = 0; counter1 < counter2; counter1++) {
  System.out.println(counter1 + ", " + counter2);
  counter2--;
}

Output:

0, 10
1, 9
2, 8
3, 7
4, 6
answered 2011-05-23T06:46:11.917

Your Answer