C++性能优化——能用array就不要用unordered_map作为查询表

发布时间 2023-04-13 10:39:28作者: 偷不走的影子

unordered_map需要哈希值计算和表查询的开销,当key值为整数且连续,直接用数组作为查询表具有更高的效率。

#include <iostream>
#include <chrono>
#include <unordered_map>
using namespace std;
long long count = 0;
constexpr int N = 10;
void timeMeasure(void(*f)()){
    auto begin = std::chrono::high_resolution_clock::now();
    uint32_t iterations = 1;
    for(uint32_t i = 0; i < iterations; ++i)
    {
        f();
    }
    auto end = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(end-begin).count();
    std::cout << duration << "ns total, average : " << duration / iterations << "ns." << std::endl;
}

std::unordered_map<uint8_t, uint8_t> dict = {
    {0U, 1U}, {1U, 2U},
    {2U, 3U}, {3U, 4U},
    {4U, 5U}, {5U, 6U},
    {6U, 7U}, {7U, 8U},
    {8U, 9U}
};

void testMap(){
    for(int i = 0; i < N; ++i){
        uint8_t index = rand() % 9;
        count += dict[index];
    }
}

constexpr uint8_t arr[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9};

void testArr(){
    for(int i = 0; i < N; ++i){
        int index = rand() % 9;
        count += arr[index];
    }
}

int main(){
    timeMeasure(testMap);
    timeMeasure(testArr);
    return 0;
}
5280ns total, average : 5280ns.
773ns total, average : 773ns.