Karp 的技术博客

在数据库中要直接存储键值对,PHP中提供的json_encodeserialize都可以满足需求。在具体的性能对比上,网上查看比人的说法,包括国外网站上说的,基本上都是在编码和空间上json_encode效率会高很多,在解码上unserlize会比较快。

经过实际环境下测试,测试结果与以上说法并不全部一致。

测试版本PHP7.1.7

测试结果:

1、在存储空间上json编码确实是很有优势的;
2、当编码的对象比较简单时,如只有一两个数组项组成的额一位数组,执行速度上json_encodeserialize要快;
3、当编码对象项比较多或组成比较复杂时,执行速度上serializejson_encode要快;
4、在解码速度上,unserializjson_decode要快。

写脚本测试了一下:

$i = 0;
$data = array_fill(0,100, 1);
while($i < 1000000) {
    json_encode($data);
    //json_decode($data, true);
    $i++;
}
$i = 0;
$data = array_fill(0,100, 1);
while($i < 1000000) {

    serialize($data);
    //unserialize($data);
    $i++;
}

分别根据序列化及反序列化测试:
简单数组序列化 json_encode 胜出

#time php7 index.php index serialize
real    0m3.676s
user    0m3.559s
sys    0m0.034s
#time php7 index.php index json_encode
real    0m2.078s
user    0m1.959s
sys    0m0.036s

简单数组反序列化 json_encode 胜出

#time php7 index.php index json_decode
real    0m10.986s
user    0m10.446s
sys    0m0.038s
#time php7 index.php index unserialize
real    0m7.111s
user    0m6.893s
sys    0m0.037s

复杂数组 序列化 serialize 胜出

time php7 index.php index serialize
real    0m43.277s
user    0m41.875s
sys    0m0.059s
time php7 index.php index json_encode
real    1m0.988s
user    0m59.110s
sys    0m0.067s

复杂数组 反序列化 unserialize 胜出 (but 并不怎么明显)

$i = 0;
//$data = array_fill(0,100, 1);
$data = '{"c_id"...322"}';
while($i < 1000000) {
  //json_encode($data);
  json_decode($data, true);
  $i++;
}

$i = 0;
//$data = array_fill(0,100, 1);
$data = 'a:4:{s:4:"......2";}';
while($i < 1000000) {
  //serialize($data);
  unserialize($data);
  $i++;
}

测试结果:

time php7 index.php index unserialize
real    1m47.532s
user    1m40.669s
sys    0m0.140s

time php7 index.php index json_decode
real    3m50.987s
user    3m43.805s
sys    0m0.271s

php

版权属于:karp
作品采用:本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。
更新于: 2024年10月17日 09:01
3

目录

来自 《PHP json_encode/json_decode与serialize/unserializ性能测试》
774 文章数
0 评论量
9 分类数
779 页面数
已在风雨中度过 9年277天3小时9分