4

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 ?

1

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Just one call and running both in the same script isn't really a benchmark is it ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.