Is there any performance difference between HashMap and LinkedHashMap for traversal through values() function?
Is there any performance difference between HashMap and LinkedHashMap for traversal through values() function?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I think the
LinkedHashMaphas to be faster in traversal due to a superiornextEntryimplementation in itsIteratorHere is why :
Let us go step by step from the
valuesimplementation.The
HashMapimplementation ofvaluesis this :The
LinkedHashMapextends fromHashMapand inherits the same implementation.The difference is in the
Iteratorimplementation for theValuesin both.for
HashMapit extends fromjava.util.HashMap.HashIteratorbut for
LinkedHashMapit extends fromjava.util.LinkedHashMap.LinkedHashIteratorso the difference essentially boils down to
nextEntryimplementation.For
LinkedHashMapit is just calling e.after where e is theEntry,but for
HashMapthere is some work involved in traversing theEntry[]array to find the next next.UPDATE : Code for
nextEntry()inHashMapThe Entry[] is not a contiguous store. (There could be null values in between). If you take a look at the above code, what it does is point next to current and find the next next by iterating over the Entry[] .
But I think this performance gain will come at the cost of insertion. Check out the
addEntrymethod in both classes as an exercise.