取决于你的轻重缓急。
如果性能是你绝对的驾驶特点,那么一定要使用最快的。在做出选择之前,一定要充分理解这些差异。不像
serialize()您需要添加额外的参数以保持UTF-8字符不受影响:
json_encode($array, JSON_UNESCAPED_UNICODE)(否则,它会将UTF-8字符转换为Unicode转义序列)。
JSON将没有对象的原始类的内存(它们总是被还原为stdClass的实例)。
你不能利用
__sleep()和
__wakeup()用JSON
默认情况下,只有公共属性使用JSON序列化。(在
PHP>=5.4你可以实现若要更改此行为,请执行以下操作。
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 themif ($jsonTime
printf("json_encode() was roughly %01.2f%% faster than serialize()\n", ($serializeTime / $jsonTime - 1) * 100);}else if ($serializeTime
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
$node = array();
foreach ($seed as $key) {
$node[$key] = fillArray($depth + 1, $max);
}
return $node;
}
return 'empty';}