正儿八经的问题,为什么网上的人说 json_encode 的效率比 serialize 高,而我自己测试则相反? PHP 数组保存在文件应该选择哪种方式比较好?

2020-07-16 17:08:25 +08:00
 frozenway

我把一个 php 数组分别保存为 serialize 和 json,然后

$start = microtime(true);
for($i = 0; $i < 1000; $i++){
    $ser = file_get_contents('gdip.ser');
    $arr = unserialize($ser);
}
$l = microtime(true) - $start;
echo $l."\n";
//
$start = microtime(true);
for($i = 0; $i < 1000; $i++){
    $json = file_get_contents('gdip.json');
    $arr = json_decode($json, true);
}
$l = microtime(true) - $start;
echo $l."\n";

然后运行得到的结果

0.939453125
2.0195319652557

这能不能说明保存成 serialize 格式读取效率更快?

3158 次点击
所在节点    PHP
25 条回复
frozenway
2020-07-16 17:48:23 +08:00
@lovecy 写在里面是为了测 serialize 文件存储的大小比 json 的大的情况下,读取并反序列成数组的效率比 json 的如何,确保文件大小更大的情况下,依然读取更快
NerverLibis
2020-07-16 17:49:34 +08:00
print_r 序列化 两件套,2020 年还有用 php 的吗
wnpllrzodiac
2020-07-16 17:50:07 +08:00
google protobuf 啊。json 太落伍了
durban126
2020-07-16 17:55:48 +08:00
重新发一个吧 标题跟内容都不符了
frozenway
2020-07-16 17:59:06 +08:00
@durban126 不发了,下班走人

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/690636

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX