第一个虽然是为什么不使用简单的md5函数?
尝试自己写哈希
function djb2($s){
$word = str_split($s);
$length = count($word);
$hashAddress = 5381;
for ($counter = 0; $counter < $length; $counter++){
$hashAddress = (($hashAddress << 5) + $hashAddress) + $word[$counter];
}
return $hashAddress;
}
echo djb2("stackoverflow");
问题是当它以这种方式实现时,这是相当缓慢的.测试显示,比md5慢3〜3倍.所以我们必须找到最快的internal implementation of a hash function.
找到最好的内部哈希
只需要把所有的algos,并测量时间来散列一百万个字符串.
function testing($algo, $str) {
$start = microtime(true);
for($ax = 0; $ax < 1000000; $ax++){
hash($algo, $str);
}
$end = microtime(true);
return ($end - $start);
}
$algos = hash_algos();
$times = [];
foreach($algos as $algo){
$times[$algo] = testing($algo, "stackoverflow");
}
// sort by time ASC
asort($times);
foreach($times as $algo => $time){
echo "$algo -> " . round($time, 2)."sec\n";
}
我的结果是:
fnv1a32 -> 0.29sec
fnv132 -> 0.3sec
crc32b -> 0.3sec
adler32 -> 0.3sec
crc32 -> 0.31sec
joaat -> 0.31sec
fnv1a64 -> 0.31sec
fnv164 -> 0.31sec
md4 -> 0.46sec
md5 -> 0.54sec
...
md2 -> 6.32sec
结果从执行到执行稍微改变 – 前8个algos由于其速度快而依赖于服务器负载而进行混洗.
应该选择什么?
你可以使用上面的8项功能:$hash = hash(‘crc32’,$string);.其实广泛使用的md5功能比领导者慢了1.7倍.
奖金