Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance and Memory allocation comparison between List and Set

I want to know the comparison between List and Set in terms of performance,memory allocation and usability.

If i don't have any requirement of keeping the uniqueness in the list of objects, neither required the insertion order to be maintained, Can I use ArrayList and SortedSet/HashSet interchangeably? Will it be good to directly use Collections class instead of even list/set?

P.S. I also don't have any need for list or set specific functions provided by java. I am using List/Set instead of Array only because they can dynamically grow without extra programming efforts.

like image 651
Priyank Doshi Avatar asked May 29 '12 12:05

Priyank Doshi


People also ask

Which is faster Set or List in Java?

As Will has noted, because of the dictionary structure HashSet is probably a bit slower than an ArrayList (unless you want to insert "between" existing elements). It also is a bit larger.

Are sets more efficient than lists Java?

If you will compare, searching between List and Set, Set will be better because of the underline Hashing algorithm.

What is the difference between List vs Set?

The main difference between List and Set is that List allows duplicates while Set doesn't allow duplicates. List is an ordered collection it maintains the insertion order, which means upon displaying the list content it will display the elements in the same order in which they got inserted into the list.


1 Answers

HashSet consumes about 5.5 times more memory than ArrayList for the same number of elements (although they're both still linear), and has significantly slower iteration (albeit with the same asymptotics); a quick Google search suggests a 2-3x slowdown for HashSet iteration versus ArrayList.

If you don't care about uniqueness or the performance of contains, then use ArrayList.

like image 175
Louis Wasserman Avatar answered Sep 20 '22 13:09

Louis Wasserman