Map lookup performance

collections, java, performance

Solution

`Map` is an interface, so the implementing classes have quite a bit of freedom in how they implement each operation (it's entirely possible to write a class that buffers the last entry, which may allow constant time access for the `get` operation if it's the same as the last gotten object, making the two practically equivalent, except for a presumably required comparison).

For `TreeMap` and `HashMap`, for example, `containsKey` is essentially just a `get` operation (more specifically `getEntry`) with a check for `null`.

Thus, for these two containers, the first version should take roughly twice as long as the second (assuming you use the same type of `Map` in both cases).

Note that `HashMap.get` is O(1) (with a hash function well-suited to the data) and `TreeMap.get` is O(log n). So if you do any significant amount of work in the loop, and the `Map` doesn't contain in the order of millions of elements, the difference in performance is likely to be negligible.

However, note the disclaimer in the docs for `Map.get`:

If this map permits null values, then a return value of null does not necessarily indicate that the map contains no mapping for the key; it's also possible that the map explicitly maps the key to null. The containsKey operation may be used to distinguish these two cases.

Problem

I'd like to do something using a map value for a given key only if the map contains the given key. Naively I would write: ``` Map<String, String> myMap = ...; if(myMap.containsKey(key)) { String value = myMap.get(key); // Do things with value } ``` The code above looks easy to understand, but from a performance point of view, wouldn't it be better the following code? ``` Map<String, String> myMap = ...; String value = myMap.get(key); if(value != null) { // Do things with value } ``` In the second snippet I don't like the fact that `value` is declared with a wider scope. How does the performance of given cases change with respect to the Map implementation? Note: Let's assume that null values are not admitted in the map. I'm not talking about asymptotic complexity here, which is the same for both snippets

Original source