在 Dan Bernstein 著名的 Djb2 哈希函数中,我们看到它使用位运算符而不是简单乘法。为什么要使用位运算符?它是否更快?
(hash << 5) + hash = hash * 33
// Hashes word to a number
unsigned int hash(const char *word)
{
// Djb2 hash function by Dan Bernstein
unsigned long hash = 5381;
int c;
while ((c = *word++))
{
hash = ((hash << 5) + hash) + tolower(c); /* hash * 33 + c */
}
return hash % N;
}