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

前端 未结 9 1526
心在旅途
心在旅途 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:39

    I think it is not obvious which is going to be faster. You might need to profile both approaches.

    The hash map should have complexity of O(1).

    The switch (with non-contiguous keys like yours) may be optimized into a binary search (at least with GCC), which has complexity of O(log n).

    On the other hand, any operation done on a hash map will be much more expensive than an operation done in a switch.

提交回复
热议问题