这是 PHP 底层的 hash 代码,请大神指示为什么要这样写

2017-12-12 21:01:22 +08:00
 thomaswang

swith 为什么不用 default, for 循环为什么步长用 8

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 -= 8) {
        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;
}

http://www.laruence.com/2009/07/23/994.html

1757 次点击
所在节点    问与答
7 条回复
cabing
2017-12-12 21:10:24 +08:00
步长用 8 应该是个算法吧。找找常用的 hash 算法,或者去 Stack Overflow 里面问问。。

不用 default 是因为最后算出来的数据一定小于 8,再对小于 8 的数据分布做个运算。写的挺巧妙的啊。
如果为 7 下面的 hash 技术都走一次。如果为 6,除了 7 下面的代码都执行一次。
lcdtyph
2017-12-12 21:15:12 +08:00
这叫循环展开,可以降低循环的开销,降低分支预测失败带来的开销。
switch 的 default 被封装到 emptyxxx 那个宏里了。
kingwl
2017-12-12 21:47:49 +08:00
戴夫设备
function007
2017-12-12 21:51:49 +08:00
thomaswang
2017-12-12 21:59:20 +08:00
@kingwl 你们是做什么的,怎么什么都知道,我入行三年了,还是这么单纯
Kilerd
2017-12-12 22:14:56 +08:00
加强循环级并行
ryd994
2017-12-13 03:48:15 +08:00
其实编译器也会帮你做的。除非是和硬件 /协议相关,否则未必比编译器自动优化更好。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/414203

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX