Re: vector element iterator
On 2007-11-25 20:13:05 -0800, "rony.john@gmail.com" <rony.john@gmail.com> said:
Hi all,
Any performance advantage for traversing elements
from list using Iterator over get(int index) ?
It depends on the list.
For an ArrayList or Vector[0], there isn't a noticable speed difference
between using an iterator or an index, and only a minimal (one-object)
difference in memory use. For other List implementations that doesn't
always hold: iterating a LinkedList using get(int index) is O(n*n),
because each call to get counts from the nearest end of the list and
iterates to the target index from scratch, whereas using an iterator is
O(n), because the iterator remembers the last element you looked at for
you.
There are some clarity tradeoffs involved; explicitly using an iterator
is, in my opinion, very slightly less readable than calling get, but
implicit iterator use with the for-each syntax is much clearer than
either.
-Owen
[0] and you should really look at using ArrayList instead of Vector, if
you are using the latter; if nothing else, it doesn't impose
synchronization on you All The Time.