php – 为什么“hash(‘md5′,’string’)”比“md5(‘string’)”快?

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – 为什么“hash(‘md5′,’string’)”比“md5(‘string’)”快?脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
http://www.php.net/manual/en/function.hash.php#73792它表示一个测试,显示md5()函数比等效的hash()函数慢约3倍.

什么可以解释这个差异? md5()函数有什么不同和/或更多的作用?

是100%正确的,那就是如果你仍然使用PHP早期版本的PHP,例如
PHP 5.1.2到PHP 5.2.2在大多数resent稳定版本的PHP他们是一样的,md5在一些版本中运行略快

Here is a simple test in most PHP version

您还需要注意的是,标记法是错误的,位置变化会影响结果…这是如何获得更好的结果.

set_time_limit(0);
echo "<PRe>";

function m1($total) {
    for($i = 0; $i < $total; $i ++)
        hash('md5','string');
}

function m2($total) {
    for($i = 0; $i < $total; $i ++)
        md5('string');
}

function m3($total) {
    for($i = 0; $i < $total; $i ++)
        hash('sha1','string');
}

function m4($total) {
    for($i = 0; $i < $total; $i ++)
        sha1('string');
}

function m5($total) {
    for($i = 0; $i < $total; $i ++)
        hash('md5',$i);
}

function m6($total) {
    for($i = 0; $i < $total; $i ++)
        md5($i);
}

function m7($total) {
    for($i = 0; $i < $total; $i ++)
        hash('sha1',$i);
}

function m8($total) {
    for($i = 0; $i < $total; $i ++)
        sha1($i);
}

$result = array(
        'm1' => 0,'m2' => 0,'m3' => 0,'m4' => 0,'m5' => 0,'m6' => 0,'m7' => 0,'m8' => 0
);

$total = 10000;

for($i = 0; $i < 100; ++ $i) {
    foreach ( array_keys($result) as $key ) {
        $alpha = microtime(true);
        $key($total);
        $result[$key] += microtime(true) - $alpha;
    }
}

echo '<pre>';
echo "Single Run\n";
print_r($result);
echo '</pre>';

产量

Single Run
Array
(
    [m1] => 0.58715152740479                 <--- hash/md5/string
    [m2] => 0.41520881652832                 <--- md5/string
    [m3] => 0.79592990875244                 <--- hash/sha1/string
    [m4] => 0.61766123771667                 <--- sha1/string
    [m5] => 0.67594528198242                 <--- hash/md5/$i
    [m6] => 0.51757597923279                 <--- md5/$i
    [m7] => 0.90692067146301                 <--- hash/sha1/$i
    [m8] => 0.74792814254761                 <--- sha1/$i

)

Live Test

脚本宝典总结

以上是脚本宝典为你收集整理的php – 为什么“hash(‘md5′,’string’)”比“md5(‘string’)”快?全部内容,希望文章能够帮你解决php – 为什么“hash(‘md5′,’string’)”比“md5(‘string’)”快?所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。