PHP Hash算法DJBX33A源码解析与优化细节
HashTable堪称PHP架构的核心基石,这一评价毫不夸张。
无论是常规数组、关联数组,还是对象属性、函数表及符号表,PHP内部均依赖HashTable作为数据存储容器。
虽然PHP的HashTable利用拉链法处理冲突已是常识,但本文重点探讨支撑其高效运行的Hash算法及其背后蕴含的设计哲学。
PHP选用了广泛应用的DJBX33A算法(即Daniel J. Bernstein提出的Times 33 with Addition),该算法同样见于Apache、Perl及Berkeley DB等项目。对于字符串而言,这是目前公认的最优哈希方案之一,因其具备极高的运算速度且分类效果极佳,能有效减少冲突并保证分布均匀。
该算法的核心逻辑可概括为以下公式: 复制代码 代码如下: hash(i) = hash(i-1) * 33 + str[i]
在Zend引擎的头文件zend_hash.h中,可以找到PHP对这一算法的具体实现代码:
复制代码 代码如下: static inline ulong zend_inline_hash_func(char *arKey, uint nKeyLength) { register ulong hash = 5381; /* variant with the hash unrolled eight times */ for (; nKeyLength >= 8; nKeyLength -= { hash = ((hash << 5) + hash) + *arKey++; hash = ((hash << 5) + hash) + *arKey++; hash = ((hash << 5) + hash) + *arKey++; hash = ((hash << 5) + hash) + *arKey++; hash = ((hash << 5) + hash) + *arKey++; hash = ((hash << 5) + hash) + *arKey++; hash = ((hash << 5) + hash) + *arKey++; hash = ((hash << 5) + hash) + *arKey++; } switch (nKeyLength) { case 7: hash = ((hash << 5) + hash) + *arKey++; /* fallthrough... */ case 6: hash = ((hash << 5) + hash) + *arKey++; /* fallthrough... */ case 5: hash = ((hash << 5) + hash) + *arKey++; /* fallthrough... */ case 4: hash = ((hash << 5) + hash) + *arKey++; /* fallthrough... */ case 3: hash = ((hash << 5) + hash) + *arKey++; /* fallthrough... */ case 2: hash = ((hash << 5) + hash) + *arKey++; /* fallthrough... */ case 1: hash = ((hash << 5) + hash) + *arKey++; break; case 0: break; EMPTY_SWITCH_DEFAULT_CASE() } return hash; }
相较于Apache和Perl直接采用的经典Times 33算法,PHP的实现存在显著差异:
复制代码 代码如下: hashing function used in Perl 5.005: # Return the hashed value of a string: $hash = perlhash("key") # (Defined by the PERL_HASH macro in hv.h) sub perlhash { $hash = 0; foreach (split //, shift) { $hash = $hash*33 + ord($_); } return $hash; }
通过对比PHP与其他语言的Hash算法实现,可以观察到多处细致的优化改进。
最明显的区别在于,PHP并未直接使用乘以33的操作,而是采用了位运算技巧: 复制代码 代码如下: hash << 5 + hash
这种将乘法转换为位移加法的做法,显然能显著提升运算速度。
此外,代码中特别运用了循环展开(unrolled)技术。这与之前阅读过的关于Discuz缓存机制的文章有异曲同工之妙:Discuz会根据帖子热度采取不同策略,仅缓存第一页,因为多数用户不会翻阅后续页面。
秉持类似的思想,PHP鼓励对8字节以下的字符索引进行优化,它以8字节为单位使用循环展开来提升效率,这体现了开发者在细节处理上的匠心。
另外,代码中还使用了inline内联函数和register寄存器变量等优化手段,足见PHP开发团队在Hash性能优化上投入了大量心血。
最后,Hash的初始值被设定为5381。不同于Apache的Times算法和Perl的Hash算法(两者初始值均为0),选择5381的原因虽无官方明确说明,但该数字具有一些特殊数学特性:
复制代码 代码如下: Magic Constant 5381: 1. odd number 2. prime number 3. deficient number 基于这些特性,有理由相信初始值的选定有助于提供更优的数据分类效果。