As we all know, json_decode gives you the option of returning an associative array or an object. There are many other situations where we have the two options as well. Obviously in some cases using one or the other is more “appropriate” based on the type of data you’re dealing with (a group of data pertaining to one item vs. a list of items).
What I’m wondering is, is there any difference in efficiency in using one vs. the other, in terms of memory, speed, etc? I’m particularly interested in access time for a very large object – how does that compare to a very large array, and why?
Sorry if this has been discussed before, search turned up nothing. I’m writing a benchmark, which may tell me which one is better, but won’t help me understand why.
Many programmers prefer using
trueas the second argument to json_decode since the returned assoc array will be very similar to how you handle objects in javascript.Returning a proper object will require reading about how such is used and what not, and since most programmers are well familiar with associative arrays that’s more preferrable, especially if the code will be maintained by a team of developers. Code should be easily understandable.
Regarding questions about performance I don’t think you’ll need to worry about that since the bottle neck in most (all) cases will be elsewhere. Unless you are parsing a massive string, and by that I mean really huge, you shouldn’t need to make any benchmarks. I believe the difference between returning an assoc array vs a proper object will be minor.
Performance Benchmark (parsing)
I found a rather large json string here and made some adjustments to make it even bigger, final size is 84 578 bytes.
I then parsed the string using both alternatives (associative array vs object) 1 000 times each, and I ran the test three times. The results are given below:
1st run
2nd run
3rd run
Performance Benchmark (read/write)
This benchmark is to show which one of
stdObjectandArray()is faster, I’m using a parsed modified json file (bigger one) than in the previous benchmark.Each read/write test was run 100 000 times (ie. the code given below was executed that many times).
json_decode ($json_data)
json_decode ($json_data, true)
1st run
2nd run
3rd run
PHP version