Hi all,
I would like to know what is the difference between these 2.
ArrayList list = new ArrayList
for(int i=0; i<list.size(); i++){
//do stuff
}
Iterator i = list.iterator();
while(i.hasNext(){
do stuff
}
Is there performance issues?
James McGill - 09 May 2006 05:24 GMT
> Hi all,
>
[quoted text clipped - 13 lines]
>
> Is there performance issues?
One important difference is the fact that the collection may not be
modified inside the scope of an iterator (it will throw
ConcurrentModificationException).
You are only referring to ArrayList so some of the generality that's in
the Collections and List Iterator are presumably of no concern, and you
want to know if looping through an array with an integer index counter
is higher performance than using the Iterator.
That's a very good question. The Iterator is not implemented as an
indexed loop, at least not in Sun Java. The collection always has a
getter armed with the iterator's next value. Much of the collection's
internal implementation is done via the iterator. But the pieces of
ArrayList that are optimized for speed, skip bounds checking and use int
array offsets to do their work.
For comparing performance, I think you have to consider the runtime
behavior of things that are private to a class (because of inlining)
differently from things you do outside that class.
Maybe someone can get Bloch to answer this question directly. He would
know.
Owen Jacobson - 09 May 2006 05:30 GMT
On Mon, 08 May 2006 21:01:00 -0700, ahjiang wrote:
> Hi all,
>
[quoted text clipped - 13 lines]
>
> Is there performance issues?
Depends on the list. For an ArrayList specificlly, no, they're pretty
much equivalent. For other List implementations the iterator may be
faster; for a LinkedList using an Iterator will be roughly O(n) while
using get(int) will be roughly O(n*n), which will make a huge difference
in medium to large lists.
Remon van Vliet - 09 May 2006 11:42 GMT
> Hi all,
>
[quoted text clipped - 13 lines]
>
> Is there performance issues?
In the case of ArrayList the difference, like said, is minimal. Both options
above are not thread-safe and roughly equal in performance. The difference
lies in the Iterator's remove() method which allows you to "safely" remove
items while iterating. Your for loop can not (easily) remove the element of
the current iteration correctly (consider what happens if you would do a
list.remove(i)). Do not remove() is an optional operation, but it is
implemented for the iterator (and listIterator) of ArrayList.