C++: What is faster - lookup in hashmap or switch statement?

前端 未结 9 1528
心在旅途
心在旅途 2021-02-02 08:55

I have a code pattern which translates one integer to another. Just like this:

int t(int value) {
    switch (value) {
        case 1: return const_1;
        ca         


        
9条回答
  •  爱一瞬间的悲伤
    2021-02-02 09:57

    I will add my 5 cents:

    For the number of entries at about 50 std::unordered_map (hash based, O(1)) is typically slower then std::map (tree based O(ln(N))), and both of them are slower then boost::flat_map(sorted vector O(ln(N))) which I tend to use in such cases. It is not always the case that switch can be compiled to jump table, and when it is, you can simply put your values (or functions) in vector yourself and access by index. Otherwise switch is marginally faster than boost::flat_map.

    Please note the word "typically" in the beginning, if you do care about performance of this piece of code do the profiling (and share results with us :)).

提交回复
热议问题