PHP中用hash实现的数组

yipeiwu_com5年前PHP代码库
PHP中使用最多的非Array莫属了,那Array是如何实现的?在PHP内部Array通过一个hashtable来实现,其中使用链接法解决hash冲突的问题,这样最坏情况下,查找Array元素的复杂度为O(N),最好则为1.
而其计算字符串hash值的方法如下,将源码摘出来以供查备:
复制代码 代码如下:

static inline ulong zend_inline_hash_func(const char *arKey, uint nKeyLength)
{
register ulong hash = 5381;                                                   //此处初始值的设置有什么玄机么?
/* variant with the hash unrolled eight times */
for (; nKeyLength >= 8; nKeyLength -= 8) {                         //这种step=8的方式是为何?
hash = ((hash << 5) + hash) + *arKey++;
hash = ((hash << 5) + hash) + *arKey++;
hash = ((hash << 5) + hash) + *arKey++;
hash = ((hash << 5) + hash) + *arKey++;                         //比直接*33要快
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... */                             //此处是将剩余的字符hash
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;//返回hash值
}

ps:对于以下函数,仍有两点不明:
hash = 5381设置的理由?
这种step=8的循环方式是为了效率么?

相关文章

php下实现在指定目录搜索指定类型文件的函数

复制代码 代码如下:function bdir($dir,$typearr){ $ndir = scandir($dir); foreach ($ndir as $k => $v)...

PHP检测一个数组有没有定义的方法步骤

PHP检测一个数组有没有定义的方法步骤

php中定义数组的方法: 1、PHP定义数组的格式: 数组名=array(); 如:$aa=array();//这样就定义了一个数组, 之后给元素赋值: $aa[0]="90...

php中Array2xml类实现数组转化成XML实例

本文实例讲述了php中Array2xml类实现数组转化成XML的方法。分享给大家供大家参考。具体实现方法如下: 复制代码 代码如下: <?php class Array2x...

PHP 获取文件路径(灵活应用__FILE__)

__FILE__ ,是返回文件的完整路径和文件名。如果用在包含文件中,则返回包含文件名。自 PHP 4.0.2 起,__FILE__ 总是包含一个绝对路径,而在此之前的版本有时会包含一个...

php设计模式之装饰模式应用案例详解

本文实例讲述了php设计模式之装饰模式。分享给大家供大家参考,具体如下: 介绍 装饰者模式(Decorator Pattern)允许你向一个现有的对象添加新的功能,同时又不改变其结...