To evaluate if Go json.Unmarshal()
is faster or slower than PHP json_decode()
for arbitrary JSON I decided to run a quick benchmark on my 2015 MacBook Pro (Intel(R) Core(TM) i7-4870HQ CPU @ 2.50GHz).
I used this ~25Mb JSON file and ran the attached two program under Go 1.22
and PHP 8.3.2
, respectively.
My benchmarks were very unscientific but I was just looking for orders of magnitude.
Here are the results from three different runs, each:
- Unmarshalling took 31.082830437s for 100 iterations
- Unmarshalling took 30.713377126s for 100 iterations
- Unmarshalling took 30.665393891s for 100 iterations
- Decoding took 16.25067782402 seconds for 100 iterations
- Decoding took 17.178377866745 seconds for 100 iterations
- Decoding took 16.336436033249 seconds for 100 iterations
You may be suprised becayse you know PHP is interpretted and Go is compiled and you might assume that would make PHP much faster. But the fact is the PHP's json_decode()
was written in C, and Go's json.UnMarshal()
uses reflection, especially for loading a type of any
.
Go there are ways of making Go's JSON performance faster. Just follow the link to learn more.
I decided to explore of a few of them and found the main2.go
which creates a slice of struct
rather than use any
shaved 22%
off the any
time, or Unmarshalling took 23.9677021s for 100 iterations
.
Suprisingly, at least to me, switching to json.RawMessage
in main3.go
for the sub-structs Actor
, Repo
and Payload
made effectively no difference from main2.go
(Unmarshalling took 23.286783374s for 100 iterations
)
Further, dropping the fields Actor
, Repo
and Payload
in main4.go
also made effectively no difference from main2.go
or main3.go
. (Unmarshalling took 22.251595239s for 100 iterations
)
So it seems that ~22
seconds for 100
iterations is a floor for json.Unmarshal()
for the given JSON file. That tells me if you need better performance then you'll need to evaluate one of the "fast JSON" packages mentioned here.
Hope this helps.
-Mike
P.S. Someone claimed the results would be different if I had used "object" in PHP, so I added a main2.php
to test it. I had to increase the memory limit though, which I doubled to 512M
from 256M
.
The results were:
- Decoding took 17.953987836838 seconds for 100 iterations
- Decoding took 17.878257989883 seconds for 100 iterations
- Decoding took 17.94038105011 seconds for 100 iterations
The difference for objects from these results is %7.5 slower, or 17.92
vs. 16.59
seconds on average.
Just another data-point with Python3 (Macbook Pro 2019, 2,4 GHz Quad-Core Intel Core i5).