The performance of std::unordered_map
primarily depends on the following factors:
max_load_factor()
), the container will resize and rehash the elements, which can be a costly operation.Here's an example demonstrating the impact of load factor on performance:
#include <chrono>
#include <iostream>
#include <unordered_map>
int main() {
using namespace std::chrono;
std::unordered_map<int, int> map;
// Insert elements
for (int i = 0; i < 1000000; ++i) {
map[i] = i;
}
// Measure access time with default load factor
auto start = high_resolution_clock::now();
for (int i = 0; i < 1000000; ++i) {
map.at(i);
}
auto end = high_resolution_clock::now();
auto duration =
duration_cast<milliseconds>(end - start);
std::cout
<< "Access time with default load factor: "
<< duration.count() << "ms\n";
// Increase load factor and measure access time
map.max_load_factor(10.0);
map.rehash(100000);
start = high_resolution_clock::now();
for (int i = 0; i < 1000000; ++i) {
map.at(i);
}
end = high_resolution_clock::now();
duration =
duration_cast<milliseconds>(end - start);
std::cout
<< "Access time with increased load factor: "
<< duration.count() << "ms\n";
}
Access time with default load factor: 62ms
Access time with increased load factor: 426ms
In this example, increasing the load factor and reducing the number of buckets leads to a significant increase in access time due to more collisions.
To optimize the performance of std::unordered_map
:
reserve()
 to preallocate the desired number of buckets if you know the expected size of the map in advance, avoiding unnecessary rehashing.Answers to questions are automatically generated and may not have been reviewed.
std::unordered_map
Creating hash maps using the standard library's std::unordered_map
container