PHP json_decode () Result: Object vs Array?

There are 2 output options for the json_decode() function, JSON Object or Array.

 $obj = json_decode($json_string, false); 

or

 $array = json_decode($json_string, true); 

Which type works best?

+4
source share
1 answer

For the json_decode() function, people can struggle between json_decode() result as an object or an associated array. Here I completed the benchmark.

The codes used (where $json_string is the JSON output of the 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 the array is 30% ~ 50% faster than the object.

+3
source

All Articles