The following list is from the google I/O talk in 2008 called \"Dalvik Virtual Machine Internals\" its a list of ways to loop over a set of objects in order from most to least e
I felt my first answer was not satisfactory and really didn't help to explain the question; I had posted the link to this site and elaborated a bit, which covered some basic use cases, but not the nitty-gritty of the issue. So, I went ahead and did a little hands-on research instead.
I ran two separate codes:
// Code 1
int i = 0;
Integer[] array = { 1, 2, 3, 4, 5 };
for (Integer obj : array) {
i += obj;
}
System.out.println(i);
// Code 2
int i = 0;
List list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
for (Integer obj : list) {
i += obj;
}
System.out.println(i);
Of course, both print out 15
, and both use an Integer
array (no int
s).
Next, I used javap
to disassemble these and look at the bytecode. (I ignored the initialization; everything before the for
loop is commented out.) Since those are quite lengthy, I posted them at PasteBin here.
Now, while the bytecode for code 1 is actually longer, it is less intensive. It uses invokevirtual
only once (aside from the println
), and no other invocations are necessary. In code 1, it seems to optimize the iteration to a basic loop; checking the array length, and loading into our variable, then adding to i
. This appears to be optimized to behave exactly as for (int i = 0; i < array.length; i++) { ... }
.
Now, in code 2, the bytecode gets much more intensive. It has to make 2 invokeinterface
calls (both to Iterator
) in addition to every other call that is needed above. Additionally, code 2 has to call checkcast
because it is a generic Iterator
(which is not optimized, as I mentioned above). Now, despite the fact that there are less calls to load
and store
operations, these aforementioned calls involve a substantial amount more overhead.
As he says in the video, if you find yourself needing to do a lot of these, you may run into problems. Running one at the start of an Activity
, for example, probably is not too big a deal. Just beware creating many of them, especially iterating in onDraw
, for example.