浅析PHP中json_encode、json_decode与serialize、unserialize的性能测试

今天偶然在想,如果用PHP写一个类似BDB的基于文件的Key-Value小型数据库用于存储非结构化的记录型数据,不知道效率会如何?

于是便联想到PHP中的对象怎么样序列化存储性价比最高呢?接着想到了之前同事推荐的JSON编码和解码函数。
据他所说,json_encodejson_decode比内置的serializeunserialize函数要高效。
于是我决定动手实验,证实一下同事所说的情况是否属实。
实验分别在PHP 5.2.13和PHP 5.3.2环境下进行。
用同一个变量,分别用以上方式进行编码或解码10000次,并得出每个函数执行10000次所需的时间。
以下是PHP 5.2.13环境其中一次测试结果:

代码如下:

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

以下是PHP 5.3.2环境其中一次测试结果:

代码如下:

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

这次实验得到的结论是:
json_encodejson_decode的效率并没有比serializeunserialize的效率高,在反序列化的时候性能相差两倍左右,PHP 5.3执行效率比PHP 5.2略有提升。

代码如下:

<?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); 
$seri = serialize($target); 
echo json :\t\t . strlen($json) . \r\n; 
echo serialize :\t . strlen($seri) . \r\n\r\n; 
$stime = microtime(true); 
for ($i = 0; $i < 10000; $i ++) 
{ 
json_encode($target); 
} 
$etime = microtime(true); 
echo json_encode :\t . ($etime - $stime) . \r\n; 
//---------------------------------- 
$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; 
//---------------------------------- 
$stime = microtime(true); 
for ($i = 0; $i < 10000; $i ++) 
{ 
serialize($target); 
} 
$etime = microtime(true); 
echo serialize :\t . ($etime - $stime) . \r\n; 
//---------------------------------- 
$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.'; 
?>

相关学习推荐:PHP编程从入门到精通

相关文章

文章浏览阅读8.4k次,点赞8次,收藏7次。SourceCodester Onl...
文章浏览阅读3.4k次,点赞46次,收藏51次。本文为大家介绍在...
文章浏览阅读1.1k次。- php是最优秀, 最原生的模板语言, 替代...
文章浏览阅读1.1k次,点赞18次,收藏15次。整理K8s网络相关笔...
文章浏览阅读1.2k次,点赞22次,收藏19次。此网络模型提供了...
文章浏览阅读1.1k次,点赞14次,收藏19次。当我们谈论网络安...