使用字符串连接代替pack()
当打包字节时,打包的二进制数据(字符串)可以通过简单地使用chr()、连接.和foreach循环来生成:
packed = "";
foreach ( $a as $byte ) {
$packed .= chr( $byte );
}
根据原始问题,$a 是源数组,$packed 是存储在字符串变量中的生成二进制数据。
基准测试
在撰写本文时,已经有了 5 种不同的工作解决方案,如果要打包的数据量很大,值得做一个基准测试。
我已经使用 1048576 个元素的数组测试了这五个案例,以便生成 1 MB 的二进制数据。我测量了执行时间和消耗的内存。
测试环境:PHP 5.6.30 - Mac OS X - 2.2 GHz Intel Core I7
(当然只使用一个核心)
// pack with ... operator: 57 ms - 1.3 MB
// string concatentation: 197 ms - 1.3 MB
// call_user_func_array: 249 ms - 1.5 MB
// multiple pack: 298 ms - 1.3 MB
// array_reduce: 39114 ms - 1.3 MB
... 运算符直接与 pack 函数一起使用,如果是迄今为止最快的解决方案 (accepted answer)
如果... 不可用(PHP 5.6 之前的版本),this answer (string concatentation) 提出的解决方案是最快的。
每种情况下的内存使用情况几乎相同。
如果有人感兴趣,我会发布测试代码。
<?php
// Return elapsed time from epoch time in milliseconds
function milliseconds() {
$mt = explode(' ', microtime());
return ((int)$mt[1]) * 1000 + ((int)round($mt[0] * 1000));
}
// Which test to run [1..5]
$test = $argv[ 1 ];
// Test 1024x1024 sized array
$arr = array();
for( $i = 0; $i < 1024 * 1024; $i++ )
{
$arr[] = rand( 0, 255 );
}
// Initial memory usage and time
$ms0 = milliseconds();
$mem0 = memory_get_usage( true );
// Test 1: string concatentation
if( $test == '1' )
{
$data = "";
foreach ( $arr as $byte ) {
$data .= chr( $byte );
}
$test = "string concatentation";
}
// Test 2: call_user_func_array
if( $test == '2' )
{
$data = call_user_func_array("pack", array_merge(array("c*"), $arr));
$test = "call_user_func_array";
}
// Test 3: pack with ... operator
if( $test == '3' )
{
$data = pack("c*", ...$arr);
$test = "pack with ... operator";
}
// Test 4: array_reduce
if( $test == '4' )
{
$data = array_reduce($arr, function($carry, $item) { return $carry .= pack('c', $item); });
$test = "array_reduce";
}
// Test 5: Multiple pack
if( $test == '5' )
{
$data = "";
foreach ($arr as $item) $data .= pack("c", $item);
$test = "multiple pack";
}
// Output result
$ms = milliseconds() - $ms0;
$mem = round( ( memory_get_usage( true ) - $mem0 ) / ( 1024 * 1024 ), 1 );
echo "$test: $ms ms; $mem MB\n";