Эдуард Сухарев
3 min readDec 13, 2017

--

JSON serialization performance in PHP

Quite often now and then I’ve stumbled across the opinion that JMS serializer, one of the most popular JSON serialization libraries, is bulky and slow. But what exactly that “slow” is? And what alternatives do we have as PHP developers?

This question bugged me and at some point I’ve decided to investigate the problem a bit deeper. Googling didn’t help much — I didn’t find benchmarks comparing serialization tools, but rather discussions on whether to use serialize() or json_encode() when handling cache, storing objects in DB or transferring data.

But Google doesn’t know everything — especially when it comes to code — and the next place to search was GitHub. And there I did find the benchmark written by Tales Santos. It only compared Symfony serializer, JMS and Tales’ own serializer, but results resembled what all claimed: JMS was slowest of them. I’ve decided to go further and added more serializers to benchmark: OpenSoft’s Simple Serializer and Zumba JSON Serializer.

Before we proceed, I should warn that this comparison does not take into account all the fancy features of benchmarked serializers. We’re not interested in popularity and maintainability of the tools either: the most popular and actively developed Symfony serializer stands shoulder to shoulder with OpenSoft’s Simple serializer which hadn’t seen updates for more than 2 years now, and Santos’ serializer is only capable of serialization, while dropping off the deserialization contest.

So, what are the results? Even though each benchmark run might take many samples (100 by default) the results will vary between runs. All that said, JMS serializer tends to be 2–3 times slower on serialization than the fastest Santos serializer, and whopping 4–7 times slower on deserialization compared to Opensoft’s Simple serializer! Which is insane if you plan on using JMS in a project that transfers and transforms a lot of data!

The amount of developer involvement into [de]serialization logic dictates the potential speed gains here. Want a nifty single-annotation solution? Grab JMS and let the magic do all the dirty work. Don’t want to get your hands dirty but still get some more performance? Write a serializer config that describes the basics of object structures and there you go. Want to squeeze the maximum performance? You’ve got \JsonSerializable interface to implement, public class properties and even plain assoc arrays to work with — json_encode will work out of the box without additional serialization libraries.

And here’s the catch — you either get convenience in code and all the sugar of annotations or you get quick and dirty, but performant solution. It all depends on your needs and what you can afford. Be sure to choose wisely — you don’t want JSON to ruin your project performance.

--

--