php内部的数组使用hash table(拉链hash)来实现的。PHP的Hash采用的是目前最为普遍的DJBX33A (Daniel J. Bernstein, Times 33 with Addition), 这个算法被广泛运用与多个软件项目,Apache, Perl和Berkeley DB等. 对于字符串而言这是目前所知道的最好的哈希算法,原因在于该算法的速度非常快,而且分类非常好(冲突小,分布均匀).
算法核心:hash(i) = hash(i-1) * 33 + str[i]
但是php 没有简单的用
而是使用了如下的方法计算一个string的hash.
初看可能看不懂,NB的地方有三个:
1,使用了(hash << 5) + hash,而不是 hash*33,自然快了
2,使用的unrolled。PHP鼓励8位一下的字符索引, 他以8为单位使用unrolled来提高效率, 这不得不说也是个很细节的,很细致的地方.似乎傻乎乎的写了重复的8条语句,其实不然…
3, hash用到了register。而且不是0开始,是从5381开始。为啥用5381?
为啥要用33这个倍数?
源码中的注释是这样写的。
/* * DJBX33A (Daniel J. Bernstein, Times 33 with Addition) * * This is Daniel J. Bernstein's popular `times 33' hash function as * posted by him years ago on comp.lang.c. It basically uses a function * like ``hash(i) = hash(i-1) * 33 + str[i]''. This is one of the best * known hash functions for strings. Because it is both computed very * fast and distributes very well. * * The magic of number 33, i.e. why it works better than many other * constants, prime or not, has never been adequately explained by * anyone. So I try an explanation: if one experimentally tests all * multipliers between 1 and 256 (as RSE did now) one detects that even * numbers are not useable at all. The remaining 128 odd numbers * (except for the number 1) work more or less all equally well. They * all distribute in an acceptable way and this way fill a hash table * with an average percent of approx. 86%. * * If one compares the Chi^2 values of the variants, the number 33 not * even has the best value. But the number 33 and a few other equally * good numbers like 17, 31, 63, 127 and 129 have nevertheless a great * advantage to the remaining numbers in the large set of possible * multipliers: their multiply operation can be replaced by a faster * operation based on just one shift plus either a single addition * or subtraction operation. And because a hash function has to both * distribute good _and_ has to be very fast to compute, those few * numbers should be preferred and seems to be the reason why Daniel J. * Bernstein also preferred it. * * * -- Ralf S. Engelschall */
说白了,就是33即很好避免冲撞,又容易通过移位快速计算得到。两相权衡的选择。
下面说说php数组内部的结构
这个是php hashtable的定义
这个是Bucket 的定义
1,php数组的随机访问:通过bucket数组来实现随即访问,计算hash值,来找到。如果冲撞找pNext指针,来继续找。
2,php数组的顺序访问:通过pListHead来找到第一个元素,然后pListNext找到下一个,pInternalPointer表示当前访问到的。
3,pInternalPointer在每次foreach的时候,会被reset成pListHead。而list(xx,xx,xxx) = each($arr)是用的时候,要手动去reset这个数组。
4,PHP中遍历数组的顺序, 是和元素的添加先后相关的。而不是key的大小(当key是数字的时候)。
5,Bucket 定义中char arKey[1] 用到了类似c++中的结构体中的灵活数组域(flexible array member)概念。