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.
It is better to use for-each loop [more readable]
I have dumped instructions using
javap
for the following code:It doesn't optimize for me.
So if you need to choose from mentioned two, go for second, but I personally would go for
for-each
.for-each Performance
From Item 46 in Effective Java by Joshua Bloch :
See Also
Either one will do. Depending on JVM, the second may be a few clock-cycles faster, but it will be an immeasurable or insignificant difference. Beware of these types of sub-optimizations. Unless you are building a real-time system, where every CPU tick counts, they just add complexity and more sources for errors.
I would suggest using the iterator construct (as has already been suggested)
It's clear, flexible and predicatble.
The JVM can't optimize it because
size()
is a method, and JVM can't (and won't try to) determine that thesize()
will always return the same value in this context. Providedsize()
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.Simple yet effective
Sorry to say, but @Jigar's answer is incorrect. This is the correct answer. (tldr; don't use
for : each
).The results:
You can make up your own mind, but too much attribution is given to the JVM optimizer. You still have to be smart with your own code, and using
for : each
notation is NOT a good idea (almost ever). As you can see, you have a good idea by putting size in its own variable.Even though some of these optimization may be JVM-dependent (and some may kick in with the JIT), it's important to know what Java does and what Java doesn't do.
If performance is critical, use the plain counter loop, however for 98% of cases, clarity and simplicity of code is far more important (like 1000x or more) and you should use a for-each loop.
@David points out that using a counter is faster, but I would point out that even for 10,000 entries, the difference is sub-microsecond.
If you have a collection of more than 10,000 entries it is highly likely you shouldn't be brute force iterating over every possibility. It is more likely a collection with a lookup like a Map is a better solution for whatever you have in mind. If you have far less than 10,000 entries performance is less likely to be important.