V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
thomaswang
V2EX  ›  问与答

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

  •  
  •   thomaswang · 2017-12-12 21:01:22 +08:00 · 1756 次点击
    这是一个创建于 2319 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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

    7 条回复    2017-12-13 03:48:15 +08:00
    cabing
        1
    cabing  
       2017-12-12 21:10:24 +08:00   ❤️ 1
    步长用 8 应该是个算法吧。找找常用的 hash 算法,或者去 Stack Overflow 里面问问。。

    不用 default 是因为最后算出来的数据一定小于 8,再对小于 8 的数据分布做个运算。写的挺巧妙的啊。
    如果为 7 下面的 hash 技术都走一次。如果为 6,除了 7 下面的代码都执行一次。
    lcdtyph
        2
    lcdtyph  
       2017-12-12 21:15:12 +08:00 via iPhone   ❤️ 1
    这叫循环展开,可以降低循环的开销,降低分支预测失败带来的开销。
    switch 的 default 被封装到 emptyxxx 那个宏里了。
    kingwl
        3
    kingwl  
       2017-12-12 21:47:49 +08:00 via Android   ❤️ 1
    戴夫设备
    function007
        4
    function007  
       2017-12-12 21:51:49 +08:00   ❤️ 1
    thomaswang
        5
    thomaswang  
    OP
       2017-12-12 21:59:20 +08:00
    @kingwl 你们是做什么的,怎么什么都知道,我入行三年了,还是这么单纯
    Kilerd
        6
    Kilerd  
       2017-12-12 22:14:56 +08:00
    加强循环级并行
    ryd994
        7
    ryd994  
       2017-12-13 03:48:15 +08:00 via Android
    其实编译器也会帮你做的。除非是和硬件 /协议相关,否则未必比编译器自动优化更好。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4448 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 10:06 · PVG 18:06 · LAX 03:06 · JFK 06:06
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.