Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Best way to reset the value in List

 
Raymond Tong
Ranch Hand
Posts: 255
2
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 312
Java MS IE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13061
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic