Why is calling containsKey on a HashMap slower then get?
Test: http://ideone.com/QsWXF (>15% difference, run on sun-jdk-1.6.0.17)
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.
Because it does [ever so slightly] more work, see the OpenJDK 7 source.
Note that
containsKeycallsgetEntrywhilegetdirectly “does the magic lookup”.I do not know why it was done this way, and am further puzzled by the use/not use ofSee John B’s and Ted Hopps’s comments as to why this is done.getForNullKey:gethas an early code split for a null-key (note thatgetwill returnnullif the entry doesn’t exist or existed with a null value stored):While
getEntry, called fromcontainsKey, does not split togetForNullKeyand there is additional work here to check for the null-key case (for each Entry scanned in the chain):Also,
containsKeyhas the additional conditional and method call (note thatgetEntrywill return an Entry object, if said key exists, even if the stored value isnull):I suppose it could be argued that
containsKeywould benefit – in terms of “performance” – from having a specialized form (at the expense of less-DRY code), or thatgetEntrycould follow the lead ofgetwith an early null-key check .. on the other-hand, it might be argued thatgetshould be written in terms ofgetEntry😉Happy coding.