我需要在平面文件中存储多维关联数据数组以进行缓存。 我可能偶尔会遇到需要将其转换为JSON以便在我的Web应用程序中使用的情况,但是绝大多数时候,我将直接在PHP中使用该数组。
在此文本文件中将数组存储为JSON或PHP序列化数组会更有效吗? 我环顾四周,似乎在最新版本的PHP(5.3)中, json_decode
实际上比unserialize
更快。
我目前倾向于将数组存储为JSON,因为我认为如果需要的话,它很容易被人阅读,并且可以不费吹灰之力就可以在PHP和JavaScript中使用,从我的阅读中来看,它甚至可能是解码速度更快(不过不确定编码)。
有人知道有什么陷阱吗? 任何人都有良好的基准可以显示这两种方法的性能优势?
#1楼
我已经写了一篇有关该主题的博客文章:“ 缓存大型数组:JSON,序列化还是var_export? ”。 在这篇文章中,显示了序列化是小型到大型阵列的最佳选择。 对于非常大的数组(> 70MB),JSON是更好的选择。
#2楼
我也做了一个小基准。 我的结果是一样的。 但是我需要解码性能。 我注意到的地方,就像上面的几个人所说的那样,反unserialize
比json_decode
快。 unserialize
大约需要json_decode
时间的60-70%。 因此结论很简单:当需要编码性能时,请使用json_encode
;当解码时需要性能时,请使用unserialize
。 由于无法合并这两个功能,因此必须在需要更高性能的地方进行选择。
我的伪基准测试:
- 用一些随机键和值定义数组$ arr
- x <100; x ++; 序列化并json_encode一个$ arr的array_rand
- 对于y <1000; y ++; json_decode json编码的字符串-计算时间
- 对于y <1000; y ++; 反序列化序列化的字符串-计算时间
- 回显更快的结果
平均而言:反序列化在json_decode的4倍中赢得了96倍。 平均间隔1.5毫秒超过2.5毫秒。
#3楼
只是一个麻烦-如果您想将数据序列化为易于读取和理解的内容(例如JSON),但具有更高的压缩率和更高的性能,则应该签出messagepack。
#4楼
在做出最终决定之前,请注意,JSON格式对于关联数组并不安全json_decode()
会将其作为对象返回:
$config = array(
'Frodo' => 'hobbit',
'Gimli' => 'dwarf',
'Gandalf' => 'wizard',
);
print_r($config);
print_r(json_decode(json_encode($config)));
输出为:
Array
(
[Frodo] => hobbit
[Gimli] => dwarf
[Gandalf] => wizard
)
stdClass Object
(
[Frodo] => hobbit
[Gimli] => dwarf
[Gandalf] => wizard
)
#5楼
我扩大了测试范围,以包括反序列化性能。 这是我得到的数字。
Serialize
JSON encoded in 2.5738489627838 seconds
PHP serialized in 5.2861361503601 seconds
Serialize: json_encode() was roughly 105.38% faster than serialize()
Unserialize
JSON decode in 10.915472984314 seconds
PHP unserialized in 7.6223039627075 seconds
Unserialize: unserialize() was roughly 43.20% faster than json_decode()
因此json似乎编码速度更快,但解码速度却很慢。 因此,这可能取决于您的应用程序以及您最希望做什么。
#6楼
主题非常好,阅读了一些答案后,我想分享有关该主题的实验。
我有一个用例,几乎每次我与数据库对话时都需要查询一些“巨大”表(不要问为什么,只是一个事实)。 数据库缓存系统不合适,因为它不会缓存不同的请求,因此我还是讲有关PHP缓存系统。
我尝试过apcu
但是它不能满足需要,在这种情况下内存不够可靠。 下一步是通过序列化将其缓存到文件中。
该表有14355个条目,其中有18列,这些是我在读取序列化缓存时的测试和统计信息:
JSON:
就像大家都说的那样, json_encode
/ json_decode
的主要不便之处在于它将所有内容转换为StdClass
实例(或Object)。 如果需要循环,将其转换为数组可能是您要做的,是的,这增加了转换时间
平均时间:780.2毫秒; 内存使用:41.5MB; 快取档案大小:3.8MB
消息包
@hutch提到msgpack 。 漂亮的网站。 让我们尝试一下吧?
平均时间:497毫秒; 内存使用:32MB; 快取档案大小:2.8MB
更好,但是需要新的扩展。 有时会编译恐惧的人...
Ig二进制
@GingerDog提到igbinary 。 请注意,我已将igbinary.compact_strings=Off
设置为igbinary.compact_strings=Off
因为我更关心读取性能而不是文件大小。
平均时间:411.4毫秒; 内存使用:36.75MB; 缓存文件大小:3.3MB
比味精包更好。 尽管如此,这也需要编译。
serialize
/反unserialize
平均时间:477.2毫秒; 内存使用:36.25MB; 快取档案大小:5.9MB
比JSON更好的性能,数组越大, json_decode
速度json_decode
慢,但是您已经是新手了。
这些外部扩展名缩小了文件的大小,在纸面上看起来不错。 数字不会说谎*。 如果获得与标准PHP函数几乎相同的结果,那么编译扩展的意义何在?
我们还可以推断出,根据您的需求,您会选择与其他人不同的东西:
- IgBinary非常好,并且性能比MsgPack好
- Msgpack更擅长压缩数据(请注意,我没有尝试过igbinary compact.string选项)。
- 不想编译? 使用标准。
就是这样,另一种序列化方法比较可以帮助您选择一种!
*经过PHPUnit 3.7.31和php 5.5.10的测试-仅使用标准hardrive和旧的双核CPU进行解码-10个相同用例测试的平均值,您的统计信息可能有所不同
#7楼
在这里查看结果(很抱歉,将PHP代码放入JS代码框中的破解):
http://jsfiddle.net/newms87/h3b0a0ha/embedded/result/
结果:在PHP 5.4中,对大小不同的数组, serialize()
和unserialize()
都明显更快。
我在真实数据上制作了一个测试脚本,用于比较json_encode与序列化和json_decode与反序列化。 该测试在生产中的电子商务站点的缓存系统上运行。 它只是简单地获取缓存中已经存在的数据,并测试编码/解码(或序列化/反序列化)所有数据的时间,我将其放在一个易于查看的表格中。
我在PHP 5.4共享托管服务器上运行了它。
结果非常有说服力,对于这些大小数据集,序列化和非序列化无疑是赢家。 特别是对于我的用例而言,json_decode和unserialize对缓存系统而言是最重要的。 Unserialize在这里几乎是无处不在的赢家。 它通常是json_decode的2到4倍(有时是6或7倍)。
有趣的是注意到@ peter-bailey的结果有所不同。
这是用于生成结果的PHP代码:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
function _count_depth($array)
{
$count = 0;
$max_depth = 0;
foreach ($array as $a) {
if (is_array($a)) {
list($cnt, $depth) = _count_depth($a);
$count += $cnt;
$max_depth = max($max_depth, $depth);
} else {
$count++;
}
}
return array(
$count,
$max_depth + 1,
);
}
function run_test($file)
{
$memory = memory_get_usage();
$test_array = unserialize(file_get_contents($file));
$memory = round((memory_get_usage() - $memory) / 1024, 2);
if (empty($test_array) || !is_array($test_array)) {
return;
}
list($count, $depth) = _count_depth($test_array);
//JSON encode test
$start = microtime(true);
$json_encoded = json_encode($test_array);
$json_encode_time = microtime(true) - $start;
//JSON decode test
$start = microtime(true);
json_decode($json_encoded);
$json_decode_time = microtime(true) - $start;
//serialize test
$start = microtime(true);
$serialized = serialize($test_array);
$serialize_time = microtime(true) - $start;
//unserialize test
$start = microtime(true);
unserialize($serialized);
$unserialize_time = microtime(true) - $start;
return array(
'Name' => basename($file),
'json_encode() Time (s)' => $json_encode_time,
'json_decode() Time (s)' => $json_decode_time,
'serialize() Time (s)' => $serialize_time,
'unserialize() Time (s)' => $unserialize_time,
'Elements' => $count,
'Memory (KB)' => $memory,
'Max Depth' => $depth,
'json_encode() Win' => ($json_encode_time > 0 && $json_encode_time < $serialize_time) ? number_format(($serialize_time / $json_encode_time - 1) * 100, 2) : '',
'serialize() Win' => ($serialize_time > 0 && $serialize_time < $json_encode_time) ? number_format(($json_encode_time / $serialize_time - 1) * 100, 2) : '',
'json_decode() Win' => ($json_decode_time > 0 && $json_decode_time < $serialize_time) ? number_format(($serialize_time / $json_decode_time - 1) * 100, 2) : '',
'unserialize() Win' => ($unserialize_time > 0 && $unserialize_time < $json_decode_time) ? number_format(($json_decode_time / $unserialize_time - 1) * 100, 2) : '',
);
}
$files = glob(dirname(__FILE__) . '/system/cache/*');
$data = array();
foreach ($files as $file) {
if (is_file($file)) {
$result = run_test($file);
if ($result) {
$data[] = $result;
}
}
}
uasort($data, function ($a, $b) {
return $a['Memory (KB)'] < $b['Memory (KB)'];
});
$fields = array_keys($data[0]);
?>
<table>
<thead>
<tr>
<?php foreach ($fields as $f) { ?>
<td style="text-align: center; border:1px solid black;padding: 4px 8px;font-weight:bold;font-size:1.1em"><?= $f; ?></td>
<?php } ?>
</tr>
</thead>
<tbody>
<?php foreach ($data as $d) { ?>
<tr>
<?php foreach ($d as $key => $value) { ?>
<?php $is_win = strpos($key, 'Win'); ?>
<?php $color = ($is_win && $value) ? 'color: green;font-weight:bold;' : ''; ?>
<td style="text-align: center; vertical-align: middle; padding: 3px 6px; border: 1px solid gray; <?= $color; ?>"><?= $value . (($is_win && $value) ? '%' : ''); ?></td>
<?php } ?>
</tr>
<?php } ?>
</tbody>
</table>
#8楼
似乎序列化是我要使用的一种,其原因有两个:
有人指出,反序列化比json_decode更快,并且“读”情况比“写”情况更有可能。
当字符串包含无效UTF-8字符时,我遇到了json_encode的麻烦。 发生这种情况时,字符串最终将为空,从而导致信息丢失。
#9楼
Y刚刚测试了序列化和json编码和解码,加上将存储字符串的大小。
JSON encoded in 0.067085981369 seconds. Size (1277772)
PHP serialized in 0.12110209465 seconds. Size (1955548)
JSON decode in 0.22470498085 seconds
PHP serialized in 0.211947917938 seconds
json_encode() was roughly 80.52% faster than serialize()
unserialize() was roughly 6.02% faster than json_decode()
JSON string was roughly 53.04% smaller than Serialized string
我们可以得出结论,JSON编码更快,并且生成的字符串更小,但是反序列化对字符串进行解码的速度更快。
#10楼
THX-此基准代码:
我用于配置的数组结果如下:JSON编码为0.0031511783599854秒
PHP在0.0037961006164551秒内序列化 json_encode()
比serialize()
在0.0070841312408447秒内编码的JSON快约20.47%
PHP在0.0035839080810547秒内序列化 unserialize()
比json_encode()
快约97.66%
因此-根据您自己的数据进行测试。
#11楼
我已经在一个相当复杂的,轻度嵌套的,包含各种数据(字符串,NULL,整数)的多重哈希中进行了彻底的测试,并且序列化/反序列化的结果比json_encode / json_decode快得多。
json在我的测试中的唯一优势是它的“打包”大小较小。
这些都是在PHP 5.3.3下完成的,如果您需要更多详细信息,请告诉我。
这是测试结果,然后是产生它们的代码。 我无法提供测试数据,因为它会显示我不能放任不管的信息。
JSON encoded in 2.23700618744 seconds
PHP serialized in 1.3434419632 seconds
JSON decoded in 4.0405561924 seconds
PHP unserialized in 1.39393305779 seconds
serialized size : 14549
json_encode size : 11520
serialize() was roughly 66.51% faster than json_encode()
unserialize() was roughly 189.87% faster than json_decode()
json_encode() string was roughly 26.29% smaller than serialize()
// Time json encoding
$start = microtime( true );
for($i = 0; $i < 10000; $i++) {
json_encode( $test );
}
$jsonTime = microtime( true ) - $start;
echo "JSON encoded in $jsonTime seconds<br>";
// Time serialization
$start = microtime( true );
for($i = 0; $i < 10000; $i++) {
serialize( $test );
}
$serializeTime = microtime( true ) - $start;
echo "PHP serialized in $serializeTime seconds<br>";
// Time json decoding
$test2 = json_encode( $test );
$start = microtime( true );
for($i = 0; $i < 10000; $i++) {
json_decode( $test2 );
}
$jsonDecodeTime = microtime( true ) - $start;
echo "JSON decoded in $jsonDecodeTime seconds<br>";
// Time deserialization
$test2 = serialize( $test );
$start = microtime( true );
for($i = 0; $i < 10000; $i++) {
unserialize( $test2 );
}
$unserializeTime = microtime( true ) - $start;
echo "PHP unserialized in $unserializeTime seconds<br>";
$jsonSize = strlen(json_encode( $test ));
$phpSize = strlen(serialize( $test ));
echo "<p>serialized size : " . strlen(serialize( $test )) . "<br>";
echo "json_encode size : " . strlen(json_encode( $test )) . "<br></p>";
// Compare them
if ( $jsonTime < $serializeTime )
{
echo "json_encode() was roughly " . number_format( ($serializeTime / $jsonTime - 1 ) * 100, 2 ) . "% faster than serialize()";
}
else if ( $serializeTime < $jsonTime )
{
echo "serialize() was roughly " . number_format( ($jsonTime / $serializeTime - 1 ) * 100, 2 ) . "% faster than json_encode()";
} else {
echo 'Unpossible!';
}
echo '<BR>';
// Compare them
if ( $jsonDecodeTime < $unserializeTime )
{
echo "json_decode() was roughly " . number_format( ($unserializeTime / $jsonDecodeTime - 1 ) * 100, 2 ) . "% faster than unserialize()";
}
else if ( $unserializeTime < $jsonDecodeTime )
{
echo "unserialize() was roughly " . number_format( ($jsonDecodeTime / $unserializeTime - 1 ) * 100, 2 ) . "% faster than json_decode()";
} else {
echo 'Unpossible!';
}
echo '<BR>';
// Compare them
if ( $jsonSize < $phpSize )
{
echo "json_encode() string was roughly " . number_format( ($phpSize / $jsonSize - 1 ) * 100, 2 ) . "% smaller than serialize()";
}
else if ( $phpSize < $jsonSize )
{
echo "serialize() string was roughly " . number_format( ($jsonSize / $phpSize - 1 ) * 100, 2 ) . "% smaller than json_encode()";
} else {
echo 'Unpossible!';
}
#12楼
首先,我更改了脚本以进行更多基准测试(也可以运行1000次,而不仅仅是1次):
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
// Make a big, honkin test array
// You may need to adjust this depth to avoid memory limit errors
$testArray = fillArray(0, 5);
$totalJsonTime = 0;
$totalSerializeTime = 0;
$totalJsonWins = 0;
for ($i = 0; $i < 1000; $i++) {
// Time json encoding
$start = microtime(true);
$json = json_encode($testArray);
$jsonTime = microtime(true) - $start;
$totalJsonTime += $jsonTime;
// Time serialization
$start = microtime(true);
$serial = serialize($testArray);
$serializeTime = microtime(true) - $start;
$totalSerializeTime += $serializeTime;
if ($jsonTime < $serializeTime) {
$totalJsonWins++;
}
}
$totalSerializeWins = 1000 - $totalJsonWins;
// Compare them
if ($totalJsonTime < $totalSerializeTime) {
printf("json_encode() (wins: $totalJsonWins) was roughly %01.2f%% faster than serialize()\n", ($totalSerializeTime / $totalJsonTime - 1) * 100);
} else {
printf("serialize() (wins: $totalSerializeWins) was roughly %01.2f%% faster than json_encode()\n", ($totalJsonTime / $totalSerializeTime - 1) * 100);
}
$totalJsonTime = 0;
$totalJson2Time = 0;
$totalSerializeTime = 0;
$totalJsonWins = 0;
for ($i = 0; $i < 1000; $i++) {
// Time json decoding
$start = microtime(true);
$orig = json_decode($json, true);
$jsonTime = microtime(true) - $start;
$totalJsonTime += $jsonTime;
$start = microtime(true);
$origObj = json_decode($json);
$jsonTime2 = microtime(true) - $start;
$totalJson2Time += $jsonTime2;
// Time serialization
$start = microtime(true);
$unserial = unserialize($serial);
$serializeTime = microtime(true) - $start;
$totalSerializeTime += $serializeTime;
if ($jsonTime < $serializeTime) {
$totalJsonWins++;
}
}
$totalSerializeWins = 1000 - $totalJsonWins;
// Compare them
if ($totalJsonTime < $totalSerializeTime) {
printf("json_decode() was roughly %01.2f%% faster than unserialize()\n", ($totalSerializeTime / $totalJsonTime - 1) * 100);
} else {
printf("unserialize() (wins: $totalSerializeWins) was roughly %01.2f%% faster than json_decode()\n", ($totalJsonTime / $totalSerializeTime - 1) * 100);
}
// Compare them
if ($totalJson2Time < $totalSerializeTime) {
printf("json_decode() was roughly %01.2f%% faster than unserialize()\n", ($totalSerializeTime / $totalJson2Time - 1) * 100);
} else {
printf("unserialize() (wins: $totalSerializeWins) was roughly %01.2f%% faster than array json_decode()\n", ($totalJson2Time / $totalSerializeTime - 1) * 100);
}
function fillArray( $depth, $max ) {
static $seed;
if (is_null($seed)) {
$seed = array('a', 2, 'c', 4, 'e', 6, 'g', 8, 'i', 10);
}
if ($depth < $max) {
$node = array();
foreach ($seed as $key) {
$node[$key] = fillArray($depth + 1, $max);
}
return $node;
}
return 'empty';
}
我使用了以下PHP 7版本:
PHP 7.0.14(cli)(内置:2017年1月18日19:13:23)(NTS)版权所有(c)1997-2016 The PHP Group Zend Engine v3.0.0,版权所有(c)1998-2016 Zend Technologies with Zend OPcache Zend Technologies v7.0.14,版权所有(c)1999-2016
我的结果是:
serialize()(wins:999)比json_encode()快10.98%,unserialize()(wins:987)比json_decode()unserialize()(wins:987)快大约33.26%,比数组json_decode快48.35% ()
显然 ,序列化/反序列化是最快的方法,而json_encode / decode是最可移植的。
如果您考虑的情况是,序列化数据的读取/写入次数是非PHP系统的10倍或更多,则最好还是使用序列化/反序列化,并在序列化之前将其设为json_encode或json_decode就时间而言。
#13楼
如果要总结一下人们在这里所说的话,则json_decode / encode似乎比序列化/反序列化BUT更快,如果您执行var_dump,则会更改序列化对象的类型。 如果出于某种原因要保留类型,请进行序列化!
(例如,尝试stdClass vs array)
序列化/反序列化:
Array cache:
array (size=2)
'a' => string '1' (length=1)
'b' => int 2
Object cache:
object(stdClass)[8]
public 'field1' => int 123
This cache:
object(Controller\Test)[8]
protected 'view' =>
json编码/解码
Array cache:
object(stdClass)[7]
public 'a' => string '1' (length=1)
public 'b' => int 2
Object cache:
object(stdClass)[8]
public 'field1' => int 123
This cache:
object(stdClass)[8]
如您所见,json_encode / decode将所有内容都转换为stdClass,这不是那么好,对象信息丢失了...因此请根据需要进行决定,尤其是如果它不仅仅是数组...
#14楼
您可能还对https://github.com/phadej/igbinary感兴趣-它为PHP提供了不同的序列化“引擎”。
我在64位平台上使用PHP 5.3.5的随机/任意“性能”数据显示:
JSON:
- JSON编码为2.180496931076秒
- JSON在9.8368630409241秒内解码
- 序列化的“字符串”大小:13993
本机PHP:
- PHP在2.9125759601593秒内序列化
- PHP在6.4348418712616秒内未序列化
- 序列化的“字符串”大小:20769
二进制:
- WIN igbinary在1.6099879741669秒内序列化
- WIN igbinrary在4.7737920284271秒内未序列化
- WIN序列化的“字符串”大小:4467
因此,igbinary_serialize()和igbinary_unserialize()更快,并且使用更少的磁盘空间。
我如上所述使用了fillArray(0,3)代码,但是使数组键变得更长。
igbinary可以存储与PHP的本机序列化可以存储的数据类型相同的数据类型(因此对象等没有问题),并且您可以告诉PHP5.3将其用于会话处理。
另请参见http://ilia.ws/files/zendcon_2010_hidden_features.pdf-幻灯片14/15/16
#15楼
我建议您使用超级缓存,这是一种文件缓存机制,不会使用json_encode
或serialize
。 与其他PHP Cache机制相比,它使用简单,而且速度非常快。
https://packagist.org/packages/smart-php/super-cache
例如:
<?php
require __DIR__.'/vendor/autoload.php';
use SuperCache\SuperCache as sCache;
//Saving cache value with a key
// sCache::cache('<key>')->set('<value>');
sCache::cache('myKey')->set('Key_value');
//Retrieving cache value with a key
echo sCache::cache('myKey')->get();
?>
#16楼
JSON比PHP的序列化格式更简单,更快,因此应使用JSON, 除非 :
- 您正在存储深度嵌套的数组:
json_decode()
:“如果JSON编码的数据深于127个元素,则此函数将返回false。” - 您正在存储需要反序列化为正确类的对象
- 您正在与不支持json_decode的旧PHP版本进行交互
#17楼
取决于您的优先级。
如果性能是您的绝对驾驶特性,那么请务必使用最快的一种。 做出选择之前,只需确保您对差异有充分的了解
- 与
serialize()
不同,您需要添加额外的参数以保持UTF-8字符不变:json_encode($array, JSON_UNESCAPED_UNICODE)
(否则它将UTF-8字符转换为Unicode转义序列)。 - JSON将不存储该对象的原始类是什么(它们总是作为stdClass的实例还原)。
- 您无法通过JSON使用
__sleep()
和__wakeup()
- 默认情况下,仅公共属性使用JSON序列化。 (在
PHP>=5.4
您可以实现JsonSerializable来更改此行为)。 - JSON更可移植
目前可能还没有想到其他一些差异。
一个简单的速度测试来比较两者
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
// Make a big, honkin test array
// You may need to adjust this depth to avoid memory limit errors
$testArray = fillArray(0, 5);
// Time json encoding
$start = microtime(true);
json_encode($testArray);
$jsonTime = microtime(true) - $start;
echo "JSON encoded in $jsonTime seconds\n";
// Time serialization
$start = microtime(true);
serialize($testArray);
$serializeTime = microtime(true) - $start;
echo "PHP serialized in $serializeTime seconds\n";
// Compare them
if ($jsonTime < $serializeTime) {
printf("json_encode() was roughly %01.2f%% faster than serialize()\n", ($serializeTime / $jsonTime - 1) * 100);
}
else if ($serializeTime < $jsonTime ) {
printf("serialize() was roughly %01.2f%% faster than json_encode()\n", ($jsonTime / $serializeTime - 1) * 100);
} else {
echo "Impossible!\n";
}
function fillArray( $depth, $max ) {
static $seed;
if (is_null($seed)) {
$seed = array('a', 2, 'c', 4, 'e', 6, 'g', 8, 'i', 10);
}
if ($depth < $max) {
$node = array();
foreach ($seed as $key) {
$node[$key] = fillArray($depth + 1, $max);
}
return $node;
}
return 'empty';
}
#18楼
如果要缓存的信息最终将在以后的某个时间点“包含”,则可能需要尝试使用var_export 。 这样,您只能在“序列化”中选择匹配项,而不能在“反序列化”中进行匹配。
#19楼
如果要备份数据并在其他计算机上或通过FTP还原数据,则JSON更好。
例如,对于序列化,如果您将数据存储在Windows服务器上,通过FTP下载数据,然后在Linux上还原,由于charachter重新编码,该数据将不再起作用,因为序列化将字符串的长度和Unicode存储>对1个字节的字符进行UTF-8转码可能会变成2个字节长,从而导致算法崩溃。