我基本上准备短语被放入数据库,他们可能是畸形的,所以我想要存储他们的一个短哈希代替(我将只是比较他们是否存在,所以哈希是理想的)。
我假设MD5在100,000+请求时相当慢,所以我想知道什么是哈希短语的最佳方法,也许是推出我自己的哈希函数或使用哈希('md4', '…“最终会更快吗?”
我知道MySQL有MD5(),所以这将在查询端补充一点速度,但也许在MySQL中还有一个更快的哈希函数,我不知道这将与PHP一起工作。
我基本上准备短语被放入数据库,他们可能是畸形的,所以我想要存储他们的一个短哈希代替(我将只是比较他们是否存在,所以哈希是理想的)。
我假设MD5在100,000+请求时相当慢,所以我想知道什么是哈希短语的最佳方法,也许是推出我自己的哈希函数或使用哈希('md4', '…“最终会更快吗?”
我知道MySQL有MD5(),所以这将在查询端补充一点速度,但也许在MySQL中还有一个更快的哈希函数,我不知道这将与PHP一起工作。
当前回答
Adler32在我的机器上运行得最好。 md5()比crc32()更快。
其他回答
CRC32速度更快,但安全性不如MD5和SHA1。MD5和SHA1在速度上没有太大的差别。
2019年更新:这个答案是最新的。支持杂音的库在很大程度上适用于所有语言。
目前的建议是使用低语哈希族(具体参见murmur2或murmur3变体)。
杂音哈希是为最小碰撞的快速哈希而设计的(比CRC、MDx和SHAx快得多)。它非常适合用于查找重复项,并且非常适合用于HashTable索引。
事实上,许多现代数据库(Redis, ElastisSearch, Cassandra)都使用它来计算各种各样的哈希值。这个特定的算法是当前十年中许多性能改进的根源。
它也用于Bloom Filters的实现中。您应该意识到,如果您正在搜索“快速哈希”,您可能会面临一个由Bloom过滤器解决的典型问题。: -)
注意:杂音是一个通用散列,意思是非加密的。它不会阻止查找生成散列的源“文本”。哈希密码是不合适的。
更多细节:MurmurHash -它是什么?
fcn time generated hash
crc32: 0.03163 798740135
md5: 0.0731 0dbab6d0c841278d33be207f14eeab8b
sha1: 0.07331 417a9e5c9ac7c52e32727cfd25da99eca9339a80
xor: 0.65218 119
xor2: 0.29301 134217728
add: 0.57841 1105
生成这个的代码是:
$loops = 100000;
$str = "ana are mere";
echo "<pre>";
$tss = microtime(true);
for($i=0; $i<$loops; $i++){
$x = crc32($str);
}
$tse = microtime(true);
echo "\ncrc32: \t" . round($tse-$tss, 5) . " \t" . $x;
$tss = microtime(true);
for($i=0; $i<$loops; $i++){
$x = md5($str);
}
$tse = microtime(true);
echo "\nmd5: \t".round($tse-$tss, 5) . " \t" . $x;
$tss = microtime(true);
for($i=0; $i<$loops; $i++){
$x = sha1($str);
}
$tse = microtime(true);
echo "\nsha1: \t".round($tse-$tss, 5) . " \t" . $x;
$tss = microtime(true);
for($i=0; $i<$loops; $i++){
$l = strlen($str);
$x = 0x77;
for($j=0;$j<$l;$j++){
$x = $x xor ord($str[$j]);
}
}
$tse = microtime(true);
echo "\nxor: \t".round($tse-$tss, 5) . " \t" . $x;
$tss = microtime(true);
for($i=0; $i<$loops; $i++){
$l = strlen($str);
$x = 0x08;
for($j=0;$j<$l;$j++){
$x = ($x<<2) xor $str[$j];
}
}
$tse = microtime(true);
echo "\nxor2: \t".round($tse-$tss, 5) . " \t" . $x;
$tss = microtime(true);
for($i=0; $i<$loops; $i++){
$l = strlen($str);
$x = 0;
for($j=0;$j<$l;$j++){
$x = $x + ord($str[$j]);
}
}
$tse = microtime(true);
echo "\nadd: \t".round($tse-$tss, 5) . " \t" . $x;
Adler32在我的机器上运行得最好。 md5()比crc32()更快。
在哈希中实现md5比md5()快一点。 所以这可以是一个选项或其他,请尝试:
echo '<pre>';
$run = array();
function test($algo)
{
#static $c = 0;
#if($c>10) return;
#$c++;
$tss = microtime(true);
for($i=0; $i<100000; $i++){
$x = hash($algo, "ana are mere");
}
$tse = microtime(true);
$GLOBALS['run'][(string)round($tse-$tss, 5)] = "\nhash({$algo}): \t".round($tse-$tss, 5) . " \t" . $x;
#echo "\n$i nhash({$algo}): \t".round($tse-$tss, 5) . " \t" . $x;
}
array_map('test', hash_algos());
ksort($run);
print_r($run);
echo '</pre>';
你可以在http://www.dozent.net/Tipps-Tricks/PHP/hash-performance上看到