json php 数组读写_存储PHP数组的首选方法(json_encode vs序列化)

取决于你的轻重缓急。

如果性能是你绝对的驾驶特点,那么一定要使用最快的。在做出选择之前,一定要充分理解这些差异。不像

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';}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值