Speed of unpack() in PHP

I needed to extract a list of integers from a binary string. I was curious to know if PHP’s unpack function is fast compared to a custom function, so I wrote a test for it.

<?php

$filename = '<some large file>';

$unpack_time = 0.0;
$unpack_time2 = 0.0;
$unpack_custom_time = 0.0;

$fp = fopen($filename, 'rb');
while (!feof($fp)) {
	$content = fread($fp, 1048576);
	
	$start = microtime(true);
	$array = unpack('N*', $content);
	$stop = microtime(true);
	$unpack_time += ($stop - $start);
	
	$start = microtime(true);
	$array = unpack('V*', $content);
	$stop = microtime(true);
	$unpack_time2 += ($stop - $start);
	
	$start = microtime(true);
	$array = unpack_custom($content);
	$stop = microtime(true);
	$unpack_custom_time += ($stop - $start);
}
fclose($fp);

print "\$unpack_time = $unpack_time\n";
print "\$unpack_time2 = $unpack_time2\n";
print "\$unpack_custom_time = $unpack_custom_time\n";

function unpack_custom($content) {
	$len = strlen($content);
	
	$result = array();
	for ($i = 0; $i + 3 < $len; $i += 4) {
		$result[] = 
		(ord($content[$i]) << 24) + 
		(ord($content[$i + 1]) << 16) + 
		(ord($content[$i + 2]) << 8) + 
		ord($content[$i + 3]);
	}	
	return $result;
}

?>

The printout: (The numbers are the number of seconds needed to convert the file’s content into integers. The file I used was 2.67 MB in size.)

$unpack_time = 1.34654474258
$unpack_time2 = 1.44259476662
$unpack_custom_time = 127.910765171

The result matches my earlier experiment, from which I have learned that custom functions are much slower than PHP’s built-in ones. Whenever possible, use the latter. By do that, you also have less code to write and debug.