【发布时间】:2010-10-02 19:14:28
【问题描述】:
我正在生成关联数组,键值是 1..n 列的字符串连接。
会回来咬我的钥匙是否有最大长度?如果是这样,我可能会停下来,换一种方式。
【问题讨论】:
-
很好的插图 RoBorg,如果我有一个超过 128mb 的密钥,我可能会发现自己在每日 WTF 上。非常感谢。
我正在生成关联数组,键值是 1..n 列的字符串连接。
会回来咬我的钥匙是否有最大长度?如果是这样,我可能会停下来,换一种方式。
【问题讨论】:
似乎只受脚本的内存限制。
快速测试让我得到一个 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>";
【讨论】:
memcache 可能会从 $_SESSION 中截断太长的键。
PHP 中的字符串大小没有实际限制。根据the manual:
注意:字符串是没问题的 变得非常大。 PHP 没有强加 字符串大小的边界;这 唯一的限制是可用内存 运行 PHP 的计算机。
可以安全地假设这也适用于将字符串用作数组中的键,但根据 PHP 处理其查找的方式,您可能会注意到字符串变大时性能下降。
【讨论】:
在 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;
}
【讨论】: