PHP中用hash实现的数组

所属分类: 网络编程 / PHP编程 阅读数: 2028
收藏 0 赞 0 分享
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++; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //比直接*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... */ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //此处是将剩余的字符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... */ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
case 1: hash = ((hash << 5) + hash) + *arKey++; break;
case 0: break;
EMPTY_SWITCH_DEFAULT_CASE()
}
return hash;//返回hash值
}

ps:对于以下函数,仍有两点不明:
hash = 5381设置的理由?
这种step=8的循环方式是为了效率么?
更多精彩内容其他人还在看

php导出CSV抽象类实例

这篇文章主要介绍了php导出CSV抽象类及其用法示例,可实现循环导出功能,从而避免内存不足的问题,需要的朋友可以参考下
收藏 0 赞 0 分享

php实现的zip文件内容比较类

这篇文章主要介绍了php实现的zip文件内容比较类及其用法,可实现比较两个zip文件的内容,返回新增、删除、及相同的文件列表,是非常实用的技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

php实现获取及设置用户访问页面语言类

这篇文章主要介绍了php实现获取及设置用户访问页面语言类,可实现获取/设置用户访问的页面语言,如果用户没有设置访问语言,则读取Accept-Language,需要的朋友可以参考下
收藏 0 赞 0 分享

PHP+FFMPEG实现将视频自动转码成H264标准Mp4文件

最近做一个在线教学网的项目,需要实现上传任意格式视频自动为h264标准视频,使用html5播放。最终使用PHP+FFMPEG实现,在此将详细解决方案分享给大家!
收藏 0 赞 0 分享

PHP会话控制:Session与Cookie详解

这篇文章主要介绍了PHP会话控制:Session与Cookie详解,本文详细讲解了PHP中Session与Cookie的相关知识,涵盖面较广,需要的朋友可以参考下
收藏 0 赞 0 分享

PHP实现手机号码中间四位用星号(*)隐藏的自定义函数分享

这篇文章主要介绍了PHP实现手机号码中间四位用星号(*)隐藏的自定义函数分享,这是一个比较常用的功能,需要的朋友可以参考下
收藏 0 赞 0 分享

PHP获取mysql数据表的字段名称和详细信息的方法

这篇文章主要介绍了PHP获取mysql数据表的字段名称和详细信息的方法,本文同时还给出了获取数据表结构、列出数据库数据表等方法,需要的朋友可以参考下
收藏 0 赞 0 分享

PHP中的output_buffering详细介绍

这篇文章主要介绍了PHP中的output_buffering详细介绍,本文讲解了output buffering的一些高级用法,需要的朋友可以参考下
收藏 0 赞 0 分享

PHP错误Warning: Cannot modify header information - headers already sent by解决方法

这篇文章主要介绍了PHP错误Warning: Cannot modify header information - headers already sent by解决方法,需要的朋友可以参考下
收藏 0 赞 0 分享

PHP常用编译参数中文说明

这篇文章主要介绍了PHP常用编译参数中文说明,本文用详细的中文注解了PHP编译参数的作用,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多