thomaswang
V2EX  ›  问与答

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

  •  
  •   thomaswang · Dec 12, 2017 · 2248 views
    This topic created in 3098 days ago, the information mentioned may be changed or developed.

    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 replies    2017-12-13 03:48:15 +08:00
    cabing
        1
    cabing  
       Dec 12, 2017   ❤️ 1
    步长用 8 应该是个算法吧。找找常用的 hash 算法,或者去 Stack Overflow 里面问问。。

    不用 default 是因为最后算出来的数据一定小于 8,再对小于 8 的数据分布做个运算。写的挺巧妙的啊。
    如果为 7 下面的 hash 技术都走一次。如果为 6,除了 7 下面的代码都执行一次。
    lcdtyph
        2
    lcdtyph  
       Dec 12, 2017 via iPhone   ❤️ 1
    这叫循环展开,可以降低循环的开销,降低分支预测失败带来的开销。
    switch 的 default 被封装到 emptyxxx 那个宏里了。
    kingwl
        3
    kingwl  
       Dec 12, 2017 via Android   ❤️ 1
    戴夫设备
    thomaswang
        5
    thomaswang  
    OP
       Dec 12, 2017
    @kingwl 你们是做什么的,怎么什么都知道,我入行三年了,还是这么单纯
    Kilerd
        6
    Kilerd  
       Dec 12, 2017
    加强循环级并行
    ryd994
        7
    ryd994  
       Dec 13, 2017 via Android
    其实编译器也会帮你做的。除非是和硬件 /协议相关,否则未必比编译器自动优化更好。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1010 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 23:16 · PVG 07:16 · LAX 16:16 · JFK 19:16
    ♥ Do have faith in what you're doing.