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

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

    A switch construct is faster (or at least not slower).

    That's mostly because a switch construct gives static data to the compiler, while a runtime structure like a hash map doesn't.

    When possible compilers should compile switch constructs into array of code pointers: each item of the array (indexed by your indexes) points to the associated code. At runtime this takes O(1), while a hash map could take more: O(log n) at average case or O(n) at worst case, usually, and anyway a bigger constant number of memory accesses.

提交回复
热议问题