| Author |
Best way to reset the value in List
|
Raymond Tong
Ranch Hand
Joined: Aug 15, 2010
Posts: 146
|
|
Hi,
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();
List.addAll(Set);
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)
Raymond
|
 |
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.
|
S.D. MADHAN
Not many get the right opportunity !
|
 |
William Brogden
Author and all-around good cowpoke
Rancher
Joined: Mar 22, 2000
Posts: 11862
|
|
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.
Bill
|
Java Resources at www.wbrogden.com
|
 |
 |
|
|
subject: Best way to reset the value in List
|
|
|