php 字符串散列,php – 用于散列8-16字节字符串的非常快的哈希函数

第一个虽然是为什么不使用简单的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倍.

奖金

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值