Clint Clint - 22 days ago 6
Java Question

Java ArrayList for-loop optimization

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.

Answer

Checking in a loop byte-code:

12: iload_3
13: aload_2
14: invokeinterface #4,  1            // InterfaceMethod java/util/List.size:()I
19: if_icmpge     31
22: iinc          1, 1
25: iinc          3, 1
28: goto          12

Putting it in a variable byte-code:

10: aload_2
11: invokeinterface #4,  1            // InterfaceMethod java/util/List.size:()I
16: istore_3
17: iconst_0
18: istore        4
20: iload         4
22: iload_3
23: if_icmpge     35
26: iinc          1, 1
29: iinc          4, 1
32: goto          20

Seems like it's invoking it every time, so actually putting it in a variable is faster, I wouldn't worry about it tho. Be aware that I'm newbie in byte-code and I may be completely wrong.