于是便联想到PHP中的对象怎么样序列化存储性价比最高呢?接着想到了之前同事推荐的JSON编码和解码函数。
据他所说,json_encode和json_decode比内置的serialize和unserialize函数要高效。
于是我决定动手实验,证实一下同事所说的情况是否属实。
实验分别在PHP 5.2.13和PHP 5.3.2环境下进行。
用同一个变量,分别用以上方式进行编码或解码10000次,并得出每个函数执行10000次所需的时间。
以下是PHP 5.2.13环境其中一次测试结果:
<BR>json : 190 <BR>serialize : 257 <BR>json_encode : 0.08364200592041 <BR>json_decode : 0.18004894256592 <BR>serialize : 0.063642024993896 <BR>u<span>!本文来源gaodai#ma#com搞*!代#%^码网5</span><pre>搞gaodaima代码
nserialize : 0.086990833282471
DONE.
以下是PHP 5.3.2环境其中一次测试结果:
<BR>json : 190 <BR>serialize : 257 <BR>json_encode : 0.062805891036987 <BR>json_decode : 0.14239192008972 <BR>serialize : 0.048481941223145 <BR>unserialize : 0.05927300453186 <BR>DONE. <BR>
这次实验得到的结论是:
json_encode和json_decode的效率并没有比serialize和unserialize的效率高,在反序列化的时候性能相差两倍左右,PHP 5.3执行效率比PHP 5.2略有提升。
以下是我用来做测试的代码:
<BR><?php <BR>$target = array ( <BR>'name' => '全能头盔', <BR>'quality' => 'Blue', <BR>'ti_id' => 21302, <BR>'is_bind' => 1, <BR>'demand_conditions' => <BR>array ( <BR>'HeroLevel' => 1, <BR>), <BR>'quality_attr_sign' => <BR>array ( <BR>'HeroStrength' => 8, <BR>'HeroAgility' => 8, <BR>'HeroIntelligence' => 8, <BR>), <BR>); <BR>$json = json_encode($target); <BR>$seri = serialize($target); <BR>echo "json :\t\t" . strlen($json) . "\r\n"; <BR>echo "serialize :\t" . strlen($seri) . "\r\n\r\n"; <BR>$stime = microtime(true); <BR>for ($i = 0; $i < 10000; $i ++) <BR>{ <BR>json_encode($target); <BR>} <BR>$etime = microtime(true); <BR>echo "json_encode :\t" . ($etime - $stime) . "\r\n"; <BR>//---------------------------------- <BR>$stime = microtime(true); <BR>for ($i = 0; $i < 10000; $i ++) <BR>{ <BR>json_decode($json); <BR>} <BR>$etime = microtime(true); <BR>echo "json_decode :\t" . ($etime - $stime) . "\r\n\r\n"; <BR>//---------------------------------- <BR>$stime = microtime(true); <BR>for ($i = 0; $i < 10000; $i ++) <BR>{ <BR>serialize($target); <BR>} <BR>$etime = microtime(true); <BR>echo "serialize :\t" . ($etime - $stime) . "\r\n"; <BR>//---------------------------------- <BR>$stime = microtime(true); <BR>for ($i = 0; $i < 10000; $i ++) <BR>{ <BR>unserialize($seri); <BR>} <BR>$etime = microtime(true); <BR>echo "unserialize :\t" . ($etime - $stime) . "\r\n\r\n"; <BR>echo 'DONE.'; <BR>?> <BR>