在Redis中,采用Bernstein的Hash算法,具体代码如下:
unsigned int dictGenHashFunction(const unsigned char *buf, int len) {
unsigned int hash = 5381;
while (len--)
hash = ((hash << 5) + hash) + (*buf++); /* hash * 33 + c */
return hash;
}解释:
把字符串转化成一个无符号32位int类型,范围从 0x00000000U到 0xFFFFFFU,但是不可以直接用的Hash Table的索引。一般情况下 dictht数据结构中的 table成员也不会申请如此大的空间。具体做法是,再用Hash值与dictht数据结构的sizemask计算取余数。
idx = h & d->ht[table].sizemask;
本文介绍了Redis中使用的Bernstein Hash算法实现及其应用场景。该算法通过简单的循环操作将输入字符串转换为一个无符号32位整数,进而用于哈希表的索引计算。随着数据增长,Redis会动态调整哈希表大小并进行重新哈希。
597

被折叠的 条评论
为什么被折叠?



