为什么位移运算符使我的哈希函数如此之快?

时间:2017-11-29 07:05:32

标签: c hashtable bit-shift cs50 hash-function

我现在正在学习C,而且我最初为拼写检查程序构建了这个哈希函数,我在CS50 edx课程中构建。

int hashing(char *word)      
{

    unsigned int hash = 0;
    for (int i = 0, n = strlen(word); i < n; i++)
        hash += word[i];
    return hash % HTABLE_SIZE;
}

然后我偶然发现了使用位移运算符的reddit上的这个hash function

int hashing(char *word)
{
    unsigned int hash = 0;
    for (int i = 0, n = strlen(word); i < n; i++)
        hash = (hash << 2) ^ word[i];
    return hash % HTABLE_SIZE;
} 

使用此哈希函数,程序的速度从0.13秒变为0.06秒。有人可以向我解释为什么这个哈希函数要快得多吗?

1 个答案:

答案 0 :(得分:1)

我不认为shift + xor比加法更快。

但是,生成的哈希可能要快得多,因为哈希值分布得更好。