4
对于函数json_decode()
,有2个输出选项,JSON对象或数组。PHP的json_decode()输出:对象与数组?
$obj = json_decode($json_string, false);
或
$array = json_decode($json_string, true);
哪种效果更好?
对于函数json_decode()
,有2个输出选项,JSON对象或数组。PHP的json_decode()输出:对象与数组?
$obj = json_decode($json_string, false);
或
$array = json_decode($json_string, true);
哪种效果更好?
对于函数json_decode()
,人们可能会拼出输出结果作为Object或Associate Array。在这里我执行了一个基准。使用
代码(其中$json_string
是谷歌地图V3地理编码API的JSON输出):
// object
$start_time = microtime(true);
$json = json_decode($json_string, false);
echo '(' . $json->results[0]->geometry->location->lat . ',' . $json->results[0]->geometry->location->lng . ')' . PHP_EOL;
$end_time = microtime(true);
echo 'JSON Object: ' . round($end_time - $start_time, 6) . 's' . PHP_EOL;
// array
$start_time = microtime(true);
$json = json_decode($json_string, true);
echo '(' . $json['results'][0]['geometry']['location']['lat'] . ',' . $json['results'][0]['geometry']['location']['lng'] . ')' . PHP_EOL;
$end_time = microtime(true);
echo 'JSON Array: ' . round($end_time - $start_time, 6) . 's' . PHP_EOL;
我发现阵列比对象快30%〜50%。
只需一次调用并在同一个脚本中运行都不是真正的基准吧;) – Bart 2013-03-19 07:43:41