MD5 with raw_output turned on

April 11th, 2007 by William Yang

On PHP’s MD5() documentation page, tszming at gmail dot com states by calling MD5() with raw_output option turned on and call bin2hex() function to convert it to hexadecimal is 3 times faster than using just MD5() function.

This sounds stupidly impossible, surely by calling one pre-built function should be faster than calling two pre-built functions with same functionality. But tszming is right, calling MD5 along is slower than calling bin2hex(md5()).

This is my test.

First test will create 1000 randomly generated string (ASCII 0 to 250). The test array of strings will be passed to the two functions to measure the time it takes to complete the operation.

Result:

Test 1 Test 2 Test 3 Test 4 Test 5 Average
SimpleMD5 7.05 ms 6.91 ms 6.76 ms 6.74 ms 6.70 ms 6.83 ms
BinMD5 2.49 ms 2.32 ms 2.61 ms 2.45 ms 2.27 ms 2.43 ms

Test Methods:

SimpleMD5 - Convert string to MD5 hash string using MD5 without raw_output option

	foreach ($test_array as $str) {
		$tmp[] = md5($str);
	}

BinMD5 - Convert string to MD5 hash string using tszming’s method, using raw_output option and use bin2hex() to convert them to hexadecimal.

	foreach ($test_array as $str) {
		$tmp[] = bin2hex(md5($str, true));
	}

Full Source Code:

Show Code | Download md5test.txt

Note: Test enviroment is PHP5 + Windows

3 comments to “MD5 with raw_output turned on”

  1. Comment by Patrick:

    hash(’md5′, $str) is faster than the two.

  2. Comment by William Yang:

    Another interesting discovery. I will put it to the test.

  3. Comment by William Yang:

    I just made the test, looks hash(’md5′, $str) is almost the same speed, if not any faster.

    BinMD5 0.86 ms 0.81 ms 0.81 ms 0.80 ms 0.83 ms 0.82 ms
    HashMD5 0.86 ms 0.86 ms 0.87 ms 0.86 ms 0.88 ms 0.86 ms

Leave a Reply