Alex Rivera | Logout

Why is "hash('md5', 'string')" faster than "md5('string')"?

Asked 2013-03-19T12:51:06.147
13

On http://www.php.net/manual/en/function.hash.php#73792 it states a test which shows that the md5() function is about 3 times slower than the equivalent hash() function.

What can explain this difference? What does the md5() function do differently and / or more?

Edit
Report

1 Answer

5

Yes 100% correct ... that is if you are still using PHP early version of PHP such as PHP 5.1.2 to PHP 5.2.2 in most resent stable version of PHP they are the same and md5 run slightly faster in some versions

Here is a simple test in most PHP version

You also need to note that bench mark method is wrong and changing position affect the result ... This is how to get better result .

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>';

Output

Single Run
Array
(
    [m1] => 0.58715152740479                 <--- hash/md5/string
    [m2] => 0.41520881652832                 <--- md5/string
    [m3] =&
answered 2013-03-19T13:08:46.397

Your Answer