Work Hard, Expect The Worst...<br /> <br />Bimal R. Patel<br />(SCJP 1.2, SCWCD 1.4)
Originally posted by Ernest Friedman-Hill:
For ArrayList or Vector, the simple for loop with "get()" will be a little faster.
Tony Morris
Java Q&A (FAQ, Trivia)
Originally posted by Tony Morris:
Can you please explain this?
Work Hard, Expect The Worst...<br /> <br />Bimal R. Patel<br />(SCJP 1.2, SCWCD 1.4)
"I'm not back." - Bill Harding, Twister
Most of the time, worry about the clarity of the code, not little micro-performance issues like this.
Originally posted by Jim Yingst:
The creation of an Iterator does take some memory, true. But you only need to do it once for the entire loop. And most Iterators have a very small memory footprint anyway - they're typically just lightweight views into some already-existing structure.
Originally posted by ak pillai:
Could not agree more. maintainability and readability are more important than gaining some few micro-seconds.
Originally posted by Jim Yingst:
EFH already addressed this, didn't he? If there's any chance your List might be a LinkedList or other implementation which has an extremely inefficient get() method, the Iterator can be much faster.
Originally posted by Jim Yingst:
Also, if you don't have a List at all, but instead have a Set or other Collection, then you don't have a get() method, and if you want to be able to loop through the entire Collection, Iterator is your only choice. Well, that or use toArray[], but that seems a waste of memory, and unlikely to be any faster. (Not when you include the time to create and populate the array, as well as loop through it.)
Originally posted by Jim Yingst:
I would say no, in general. Unless you are sure that the ArrayList or Vector will not be changed to something else some day. If you really want to optimize performance, and don't mind writing extra code to do so (note this is probably a bad idea already, in most cases) then you can do something like this:
.
.
.
Work Hard, Expect The Worst...<br /> <br />Bimal R. Patel<br />(SCJP 1.2, SCWCD 1.4)
Consider Paul's rocket mass heater. |