Which is the most efficient way to traverse a collection?
List a = new ArrayList();
for (Integer integer : a) {
integer.toSt
The foreach
underhood is creating the iterator
, calling hasNext() and calling next() to get the value; The issue with the performance comes only if you are using something that implements the RandomomAccess.
for (Iterator<CustomObj> iter = customList.iterator(); iter.hasNext()){
CustomObj custObj = iter.next();
....
}
Performance issues with the iterator-based loop is because it is:
Iterator<CustomObj> iter = customList.iterator();
);iter.hasNext()
during every iteration of the loop there is an invokeInterface virtual call (go through all the classes, then do method table lookup before the jump).hasNext()
call figure the value: #1 get current count and #2 get total countiter.next
(so: go through all the classes and do method table lookup before the jump) and as well has to do fields lookup: #1 get the index and #2 get the reference to the array to do the offset into it (in every iteration).A potential optimiziation is to switch to an index iteration
with the cached size lookup:
for(int x = 0, size = customList.size(); x < size; x++){
CustomObj custObj = customList.get(x);
...
}
Here we have:
customList.size()
on the initial creation of the for loop to get the size customList.get(x)
during the body for loop, which is a field lookup to the array and then can do the offset into the arrayWe reduced a ton of method calls, field lookups. This you don't want to do with LinkedList
or with something that is not a RandomAccess
collection obj, otherwise the customList.get(x)
is gonna turn into something that has to traverse the LinkedList
on every iteration.
This is perfect when you know that is any RandomAccess
based list collection.