• Post Reply Bookmark Topic Watch Topic
  • New Topic

Speed: LinkedHashSet vs HashSet  RSS feed

 
alex sandoval
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi everyone! I will be taking SCJP tomorrow in the morning (GMT+8). I am doing the final exam of ExamLab by Devaka Cooray (Thanks Devaka great simulator!).

I just want to make sure if question 19 of Final exam from ExamLab is correct. It says that LinkedHashSet is faster than HashSet because it is doubly-linked. Is it true? Because I researched the API didn't find any statement that it is faster than HashSet or any other Set implementations because of its doubly-linked elements. Hope you may help me clear my thoughts before taking the exam tomorrow.

By the way, wish me luck guys! Thanks
 
wei ma
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
alex sandoval wrote:Hi everyone! I will be taking SCJP tomorrow in the morning (GMT+8). I am doing the final exam of ExamLab by Devaka Cooray (Thanks Devaka great simulator!).

I just want to make sure if question 19 of Final exam from ExamLab is correct. It says that LinkedHashSet is faster than HashSet because it is doubly-linked. Is it true? Because I researched the API didn't find any statement that it is faster than HashSet or any other Set implementations because of its doubly-linked elements. Hope you may help me clear my thoughts before taking the exam tomorrow.

By the way, wish me luck guys! Thanks


K&B page 564.

Because LinkedHashSet maitains a doubly linkedlist, it will be slower for insertion and removing, but will be slightly faster in iteration.

Not exactly same word, what that basically what it means. Good luck for your exam!
 
Punit Singh
Ranch Hand
Posts: 952
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
javadoc says:
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.


K&B says LinkedHashMap has faster iteration than HashMap, K&B does not say anything about LinkedHashSet and HashSet, so you should not worry, this question will not be in the exam, if it comes in the exam than write LinkedHashSet has faster iteration as Javadoc says that.

Another interesting fact I found from the source code is that HashSet uses internally HashMap for storage purpose, while LinkedHashSet uses LinkedHashMap for storage purpose, so now definitely LinkedHashSet is faster that HashSet.
 
alex sandoval
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That clears my thoughts now. Thanks a lot Mei and Punit!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!