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

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

    Hash table time complexity is generally O(1) when don't considering collision. C++ standard doesn't specified how switch is implemented but it can be implemented as jump-table which time complexity is O(1) too or it can be implemented as binary search which time complexity is O(log n) or a combination depending on how many case statement etc.

    So in a word, small scale like your case, switch is faster, but hash table might win in large scale

提交回复
热议问题