【问题标题】:What is the max key size for an array in PHP?PHP中数组的最大密钥大小是多少?
【发布时间】:2010-10-02 19:14:28
【问题描述】:

我正在生成关联数组,键值是 1..n 列的字符串连接。

会回来咬我的钥匙是否有最大长度?如果是这样,我可能会停下来,换一种方式。

【问题讨论】:

  • 很好的插图 RoBorg,如果我有一个超过 128mb 的密钥,我可能会发现自己在每日 WTF 上。非常感谢。

标签: php arrays key


【解决方案1】:

似乎只受脚本的内存限制。

快速测试让我得到一个 128mb 的密钥没问题:

ini_set('memory_limit', '1024M');

$key = str_repeat('x', 1024 * 1024 * 128);

$foo = array($key => $key);

echo strlen(key($foo)) . "<br>";
echo strlen($foo[$key]) . "<br>";

【讨论】:

  • 哎呀!好吧,我当然不必担心我的密钥会超过 255 个字符。
  • 请记住,PHP 可能不是密钥大小的唯一限制因素。例如,memcache 可能会从 $_SESSION 中截断太长的键。
【解决方案2】:

PHP 中的字符串大小没有实际限制。根据the manual

注意:字符串是没问题的 变得非常大。 PHP 没有强加 字符串大小的边界;这 唯一的限制是可用内存 运行 PHP 的计算机。

可以安全地假设这也适用于将字符串用作数组中的键,但根据 PHP 处理其查找的方式,您可能会注意到字符串变大时性能下降。

【讨论】:

    【解决方案3】:

    在 zend_hash.h 中,你可以找到 zend_inline_hash_func() 方法,该方法可以显示如何在 PHP 中对 key 字符串进行哈希处理,因此使用字符串长度小于 8 个字符的 key 对性能更好。

    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;   
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-07
      • 1970-01-01
      • 2014-06-13
      • 2010-10-13
      • 2013-01-09
      • 2017-06-09
      • 1970-01-01
      相关资源
      最近更新 更多