取决于你的优先级.
如果性能是你的绝对驾驶特征,那么一定要使用最快的.在你做出 Select 之前,确保你充分理解了这些差异
- 与
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';
}