Have a good hash function for a C++ hash table?

前端 未结 9 1120
鱼传尺愫
鱼传尺愫 2020-12-12 18:15

I am in need of a performance-oriented hash function implementation in C++ for a hash table that I will be coding. I looked around already and only found questions asking wh

9条回答
  •  温柔的废话
    2020-12-12 19:01

    Now assumming you want a hash, and want something blazing fast that would work in your case, because your strings are just 6 chars long you could use this magic:

    size_t precision = 2; //change the precision with this
    size_t hash(const char* str)
    {
       return (*(size_t*)str)>> precision;
    }
    

    CRC is for slowpokes ;)

    Explanation: This works by casting the contents of the string pointer to "look like" a size_t (int32 or int64 based on the optimal match for your hardware). So the contents of the string are interpreted as a raw number, no worries about characters anymore, and you then bit-shift this the precision needed (you tweak this number to the best performance, I've found 2 works well for hashing strings in set of a few thousands).

    Also the really neat part is any decent compiler on modern hardware will hash a string like this in 1 assembly instruction, hard to beat that ;)

提交回复
热议问题