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

Performance issue

Patrick Mugabe
Ranch Hand

Joined: Jan 08, 2002
Posts: 132
If I have a list and I need to return an array what would execute faster:
1) converting it an array OR
2) converting it to an iterator
as in:

1)
String [] out = new String[list.size()];
for(int i =0;i <out.length;i++){
out[i] = list.get(i);
}

OR
2)
Iterator iter = null;
int ctr = 0;
list = iter.iterator();
while(iter.hasNext(){
out[ctr++] = iter.next().toString();
}

then I return an array
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14150
    
  18

Write a small test program yourself to find out...

Note that interface List has a method toArray(...) to convert a List to an array. You don't need to do it "by hand".


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
As the previous poster said, you should not do this "by hand", but should use toArray() method.

However, if you were to do something like this "by hand", the right approach would depend on the exact type of List. An ArrayList will give slightly better performance using get(int index), whereas a LinkedList will give much better performance using Iterator. Using get(int index) on a large LinkedList will be seriously slow: O(n^2), I think.

If you do not know the actual exact type of List, it is best to use an Iterator.

In Java 5+, you can and should use "enhanced for" loop.


Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Performance issue