小编典典
取决于您的优先级。
如果性能是您的绝对驾驶特性,那么请务必使用最快的一种。做出选择之前,只需确保您对差异有充分的了解
不同于serialize()您需要添加额外的参数来保持UTF-8字符不变:(json_encode($array, JSON_UNESCAPED_UNICODE) 否则,它将UTF-8字符转换为Unicode转义序列)。
JSON将不存储该对象的原始类是什么(它们总是作为stdClass的实例还原)。
你不能充分利用__sleep(),并__wakeup()与JSON
默认情况下,仅公共属性使用JSON序列化。(PHP>=5.4您可以实现JsonSerializable来更改此行为)。
JSON更可移植
目前可能还没有想到其他一些差异。
一个简单的速度测试来比较两者
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';
}
2020-05-26