In Dov Bulka's Java Performance and Scalability: Volume 1, the author mentions that looping over an ArrayList with something such as
for (int i = 0; i < vector.size(); i++) {
// do something that does not modify vector size...
}
is actually a minor optimization issue because of the constant computation of vector.size(), thus implying that something such as
int size = vector.size();
for (int i = 0; i < size; i++) {
// do something that does not modify vector size...
}
is actually slightly more efficient. As the book was written in 2000, the author was using the Sun 1.2.2 JDK.
Does this condition still hold for newer JDKs? Or is Java compilation now smart enough to remove these inefficiencies, despite how minor they may be?
EDIT: I don't worry about these tiny optimizations in my code; I was simply curious about the evolution of the JDK.
size()is a bottleneck in your code, don't waste your time worrying about such micro-optimizations. In any case, that optimization is only safe under certain conditions (i.e. that no other thread can change the size ofvectorwhile you are in the loop).for-eachloop and not worrying about the internals of the theList<>. In java 8List#forEach(...)will hide it even more.