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

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

    An array will have the fastest access time, by definition.

    The switch statement compares values, then uses a jump table (which is an array of function pointers).

    The hashmap computes a hash value from the data, then either searches a tree in memory or uses the hash value as an index into an array. Slow because of computing the hash value.

    On most modern platforms, 64k, is not a big amount of data and can be statically allocated as a constant array.

    One problem with the array technique is account for keys that you have not accounted for. One example is to use a unique sentinel value. When the value is returned, you know you have an unknown key.

    I suggest using a static const array of values.

提交回复
热议问题