Search code examples
c++performancehashmapstd

C++ hash_map find() vs contains() performance


What's the better option performance-wise if I want to check if an element is contained in a map and use it directly afterwards?

std::unordered_map<int, std::string> my_map;
int my_key;

Option 1:

if (const auto& iter = my_map.find(my_key); iter != my_map.end()) {
      const auto& value = iter->second;
}

Option 2:

if (my_map.contains(my_key)) {
      const auto& value = my_map.at(my_key);
}

For readability I prefer option 2. However, from my understanding Option 2 should be slower since there are two hashmap lookups.


Solution

  • You are correct.

    Using find is more efficient since there is only the one lookup being performed whereas the second option of using contains is less efficient because you have to also perform the at lookup.