在数据库中要直接存储键值对,PHP中提供的json_encode与serialize都可以满足需求。在具体的性能对比上,网上查看比人的说法,包括国外网站上说的,基本上都是在编码和空间上json_encode效率会高很多,在解码上unserlize会比较快。
经过实际环境下测试,测试结果与以上说法并不全部一致。
测试版本PHP7.1.7。
测试结果:
1、在存储空间上json编码确实是很有优势的;
2、当编码的对象比较简单时,如只有一两个数组项组成的额一位数组,执行速度上json_encode比serialize要快;
3、当编码对象项比较多或组成比较复杂时,执行速度上serialize比json_encode要快;
4、在解码速度上,unserializ比json_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