php implode/explode, serialize, json, msgpack 性能對(duì)比
首先使用implode, serialize, json_encode, msgpack_pack創(chuàng)建四個(gè)文本文件屈芜,用于測(cè)試。
創(chuàng)建代碼如下:
<?php
$arr = array(
'content1' => '一二三四五六七八九十',
'content2' => '一二三四五六七八九十',
'content3' => '一二三四五六七八九十'
);
echo file_put_contents('implode.txt', implode(',',$arr), true).'<br>';
echo file_put_contents('serialize.txt', serialize($arr), true).'<br>';
echo file_put_contents('json.txt', json_encode($arr), true).'<br>';
echo file_put_contents('msgpack.txt', msgpack_pack($arr), true);
?>
比較 implode, serialize, json_encode, msgpack_pack 性能
<?php
$arr = array(
'content1' => '一二三四五六七八九十',
'content2' => '一二三四五六七八九十',
'content3' => '一二三四五六七八九十'
);
$start = microtime(true);
$i = 1000000;
while($i>0){
// 分別測(cè)試運(yùn)行時(shí)間及內(nèi)存使用情況
$tmp = implode(',',$arr);
// $tmp = serialize($arr);
// $tmp = json_encode($arr);
// $tmp = msgpack_pack($arr);
$i--;
}
$end = microtime(true);
echo 'run time:'.($end-$start).'s<br>';
echo 'memory usage:'.(memory_get_usage()/1024).'KB';
?>
implode 1.3225722312927s 628.50KB
serialize 2.0553789138794s 628.32KB
json_encode 2.5058920383453s 628.34KB
msgpack_pack 1.6431028842926s 628.24KB
結(jié)果:內(nèi)存使用情況差不多姿骏,運(yùn)行時(shí)間 implode < msgpack_pack < serialize < json_encode
比較 explode, unserialize, json_decode, msgpack_unpack 性能
<?php
$data = file_get_contents('implode.txt');
//$data = file_get_contents('serialize.txt');
//$data = file_get_contents('json.txt');
//$data = file_get_contents('msgpack.txt');
$start = microtime(true);
$i = 1000000;
while($i>0){
$tmp = explode(',',$data);
//$tmp = unserialize($data);
//$tmp = json_decode($data, true);
//$tmp = msgpack_unpack($data);
$i--;
}
$end = microtime(true);
echo 'run time:'.($end-$start).'s<br>';
echo 'memory usage:'.(memory_get_usage()/1024).'KB';
?>
explode 1.7446749210358s 628.74KB
unserialize 2.1386790275574s 628.67KB
json_decode 5.2423169612885s 628.84KB
msgpack_unpack 2.2290098667145s 628.63KB
結(jié)果:內(nèi)存使用情況差不多戴甩,運(yùn)行時(shí)間 explode < serialize < msgpack_unpack < json_decode
總結(jié)肉微,由于implode/explode不適合使用復(fù)雜的結(jié)構(gòu)酪惭,因此常用的為serialize,json,msgpack三種氯哮。
而三種比較,運(yùn)行速度躏敢,內(nèi)存占用,空間占用最優(yōu)為msgpack, 其次是serialize整葡,最后是json件余。
如有條件,建議使用msgpack序列化處理數(shù)據(jù)。
轉(zhuǎn)自 https://blog.csdn.net/fdipzone/article/details/43679337