aspose file tools*
The moose likes Performance and the fly likes Iterator or for loop Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Performance
Bookmark "Iterator or for loop" Watch "Iterator or for loop" New topic
Author

Iterator or for loop

David Jon
Greenhorn

Joined: Feb 16, 2001
Posts: 17
Does anyone have any thoughts about whether it is faster to Have a List and use an Iterator to move through it or to convert the List into an array and use a for loop to move through it.
D.
John Bateman
Ranch Hand

Joined: Mar 09, 2000
Posts: 320
Accessing Arrays directly via their 'element' are much faster than any type of collection that uses an iterator/enumerator.
I have read somewhere that you can get from 2 to 13 times better performance out of an array with element address as compared to collections like Vectors, Lists, ArrayLists and their iterators/enumerators etc.
I guess you would have to now judge what the cost of converting this list into a array will be?
I.E.
If the results of your testing looks like this..
(these are made up numbers)
iterating through list via iterator: 24ms
iterating through array via for loop and element address: 3ms
converting list to array = 20ms.
Do you really want to have the extra object creation to save you 1ms? Maybe, maybe not.
The thing with performance that I've noticed is that everything has an opportunity cost.
Two good books on this topic.
(I'm going to add this first one to my signature)
- Practical Java by Peter Haggar (Addison-Wesley)
- Performance Tuning by Jack Shirasi (O'Reilly)

[This message has been edited by John Bateman (edited March 01, 2001).]


SOURCE CODE should be SURROUNDED by "code" tags.
Peter den Haan
author
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
Originally posted by David Jon:
Does anyone have any thoughts about whether it is faster to Have a List and use an Iterator to move through it or to convert the List into an array and use a for loop to move through it.

The first question will have to be: how many times do you plan to iterate through that list? Iterating may be slower-than-optimal, but so is converting a List to an array. If you're only going to iterate once, it's probably not worth it. When does it start to become worth it? -- that requires quantitative analysis (i.e. trying out ), I don't know.
- Peter
[This message has been edited by Peter den Haan (edited March 02, 2001).]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Iterator or for loop