性能比较

同一个变量编码或解码10000次,每个函数执行10000次所需时间

php5.2.13

json : 190 
serialize : 257 
json_encode : 0.08364200592041 
json_decode : 0.18004894256592 
serialize : 0.063642024993896 
unserialize : 0.086990833282471 
DONE.

时间

json_decode两倍于unserialize

php5.3.2

json : 190 
serialize : 257 
json_encode : 0.062805891036987 
json_decode : 0.14239192008972 
serialize : 0.048481941223145 
unserialize : 0.05927300453186 
DONE.

json_decode两倍于unserialize

总之 unserialize 解码速度要更快,在做缓存,编码频繁解码的情况下使用会有更好的效率。

测试代码如下

<?php
$target = array (
'name' => '全能头盔',
'quality' => 'Blue',
'ti_id' => 21302,
'is_bind' => 1,
'demand_conditions' => array (
'HeroLevel' => 1,
),
'quality_attr_sign' => array (
'HeroStrength' => 8,
'HeroAgility' => 8,
'HeroIntelligence' => 8,
),
); $json = json_encode($target); //json_encode编码
$seri = serialize($target); //serialize序列化
echo "json :\t\t" . strlen($json) . "\r\n"; //json_encode后字符串长度
echo "serialize :\t" . strlen($seri) . "\r\n\r\n"; //serialize序列化长度 //---------------------------------- json_encode
$stime = microtime(true); //起始微秒
for ($i = 0; $i < 10000; $i ++){ //10000次
json_encode($target);
}
$etime = microtime(true); //终止微秒
echo "json_encode :\t" . ($etime - $stime) . "\r\n"; //运行时间 //---------------------------------- json_decode
$stime = microtime(true);
for ($i = 0; $i < 10000; $i ++){
json_decode($json);
}
$etime = microtime(true);
echo "json_decode :\t" . ($etime - $stime) . "\r\n\r\n"; //---------------------------------- serialize
$stime = microtime(true);
for ($i = 0; $i < 10000; $i ++){
serialize($target);
}
$etime = microtime(true);
echo "serialize :\t" . ($etime - $stime) . "\r\n"; //---------------------------------- unserialize
$stime = microtime(true);
for ($i = 0; $i < 10000; $i ++){
unserialize($seri);
}
$etime = microtime(true);
echo "unserialize :\t" . ($etime - $stime) . "\r\n\r\n";
echo 'DONE.';
?>

json : 190

serialize : 257

json_encode : 0.052663087844849

json_decode : 0.068554162979126

serialize : 0.023483037948608

unserialize : 0.031199216842651

DONE.

05-11 11:36