php数组序列化,存储PHP数组的首选方法(json_encode与序列化)

小编典典

取决于您的优先级。

如果性能是您的绝对驾驶特性,那么请务必使用最快的一种。做出选择之前,只需确保您对差异有充分的了解

不同于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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值