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

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

    The speed of a hash map will depend on two things: the speed of the hash function, and the number of collisions. When all of the values are known ahead of time, it's possible to create a perfect hash function that has no collisions. If you can generate a perfect hash function that only consists of a couple of arithmetic operations, it will potentially be faster than the switch.

提交回复
热议问题