thomaswang
V2EX  ›  问与答

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

  •  
  •   thomaswang · Dec 12, 2017 · 2590 views
    This topic created in 3248 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
    cabing
    Dec 12, 2017❤️1
    1
    步长用 8 应该是个算法吧。找找常用的 hash 算法,或者去 Stack Overflow 里面问问。。

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