For the function json_decode()
, there are 2 options of output, JSON Object or Array.
$obj = json_decode($json_string, false);
or
$array = json_decode($json_string, true);
Which type performs better ?
For the function json_decode()
, there are 2 options of output, JSON Object or Array.
$obj = json_decode($json_string, false);
or
$array = json_decode($json_string, true);
Which type performs better ?
For the function json_decode()
, people may struggle between output the result as Object or Associate Array. Here I performed a benchmark.
Codes used ( where $json_string
is a JSON output of Google Maps V3 Geocoding API ):
// 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;
I found that Array is 30% ~ 50% faster than Object.