This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Performance and the fly likes Best way to reset the value in List Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Performance
Bookmark "Best way to reset the value in List" Watch "Best way to reset the value in List" New topic

Best way to reset the value in List

Raymond Tong
Ranch Hand

Joined: Aug 15, 2010
Posts: 238


I have got a List with approximate 60k elements
and a Set with approximate 40k elements.

I need to reset the List to point to the elements inside the Set.
I found 2 approachs and have done some benchmark test but could not give me much information.

1) List.clear();

2) List = Arrays.asList(Set.toArray());

Which one would have better performance or there would have a better alternative?
(The size of List and Set may varies)

Madhan Sundararajan Devaki
Ranch Hand

Joined: Mar 18, 2011
Posts: 312

I believe, in option 1, you are re-using the List object, whereas in option 2, you are destroying existing List object and then creating a new one.

I guess, option 1 is preferable.

Not many get the right opportunity !
William Brogden
Author and all-around good cowpoke

Joined: Mar 22, 2000
Posts: 13037
The clear operation on an existing list does this:

(java.util.ArrayList source)
operating on every single element! Therefore it will be slow slow slow compared to creating a new empty list.

Furthermore, if you can create the new list with the required size, as option 2 does, you avoid the expansion overhead.

I agree. Here's the link:
subject: Best way to reset the value in List
It's not a secret anymore!