In Java, having a HashMap fully filled in with data of such form:
HashMap<Integer, int[]> map = new HashMap<Integer, int[]>(1000000, 1);
what is faster when checking the existence of a random key, say 100:
if (map.get(100) == null))
or
if (!map.containsKey(100))
?
Question is interesting from the micro-optimization point of view.
The
containsKeyshould be very slightly slower because it results in an extra function call (it just callsgetEntry) (it could get optimised away, I’m not sure whether Java will do so).containsKeylooks like:But note that
containsKeycould on the other hand be very slightly faster on otherMapimplementations (but probably not those in the standard Java API).Generally my implementations look like: (avoiding the need for
containsKey)The below would definitely be slower than the above: (if the items you look for exist a reasonable amount of the time)
Edit: Thanks to zvzdhk for providing the source of
containsKey. I should actually have checked.