So im developing a program where I need to store unique customer data of primitive types. In this regard, I have been reading a book about datastructures, and came to the conclusion to use a HashSet
.
Now this book states, that a HashSet
has faster insertion and removal, than a LinkedHashSet
. Now this baffles me a bit. I thought that the only difference between the two, was that a LinkedHashSet
uses some extra memory, using a LinkedList
to keep order.
Can anyone elaborate?
Choose you Data Structure wisely.
You can use Linked Hash Set instead of Hash Set if the order of insertion is important to you. With the additional features the memory or processor cycles might take a hit.
Edit1 : Things to consider other than the insertion order: Because LinkedHashSet maitains a doubly linkedlist, it will be slower for insertion and removing, but will be slightly faster in iteration.
To Quote the java doc:
This class provides all of the optional Set operations, and permits null elements. Like HashSet, it provides constant-time performance for the basic operations (add, contains and remove), assuming the hash function disperses elements properly among the buckets. Performance is likely to be just slightly below that of HashSet, due to the added expense of maintaining the linked list, with one exception: Iteration over a LinkedHashSet requires time proportional to the size of the set, regardless of its capacity. Iteration over a HashSet is likely to be more expensive, requiring time proportional to its capacity.