Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Performance issue

 
Patrick Mugabe
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 15356
39
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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".
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic