4

functionjson_decode()には、JSON オブジェクトまたは配列の 2 つの出力オプションがあります。

$obj = json_decode($json_string, false);

また

$array = json_decode($json_string, true);

どちらのタイプがより良いパフォーマンスを発揮しますか?

4

1 に答える 1

3

関数の場合json_decode()、人々は結果をオブジェクトとして出力するか、連想配列として出力するかで苦労するかもしれません。ここでベンチマークを実行しました。

使用されるコード ($json_stringは Google Maps V3 Geocoding 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;

Array は Object よりも 30% ~ 50% 高速であることがわかりました。

于 2013-03-19T07:32:13.817 に答える