serialize() vs json_encode()

Posted on 04.05.2015 21:05:09 in PHP, Webcoding 0 Comments


Some of you might know the problem: You have to store a dynamic array of values in your database. But what’s the fastest solution on the php side? What’s better for the database? Any more pros and cons? I did a bit of testing and came to conclusion that json is the way to go, if you have to store an array as value to your database.



I tested both with an multidimensional array consisting of 3 layers and 5 values on each layer. The last layer has random strings that have 6 chars each. I repeated the test 50 times. Here are my results:


The serialize() function needed about 76% longer than json_encode(). While serialize() needed around 0.064 ms, json_encode() did it in only 0.036 ms.


The unserialize() function was 21% faster than json_decode(). While unserialize() needed only 0.067 ms, json_decode() did need 0.085ms. So the serialize functions seem to need around the same time to serialize/unserialize, but jsons encoding seems to be a bit faster than the decoding.


But what about the size of the serialized / encoded arrays? I think this is one of the most important things, as the processing only takes milliseconds. In this case json is the big winner. The serialized array string was 12.123 chars long and the json string only 5.878. If you really have to store an large amount of data, you should go with json. Especially if you want to take care of your database size.


All in all I would say… json is the big winner, not only the size the speed is als better. But if you want constant speed you’re fine to go with serialize. But also think of the better usage of json. You can easily use it with your javascript, so you might don’t need to decode it. If you have really really big arrays, json becomes quite slow on decode, in this case I would prefer the unserialize function. As you might see, there are pros and cons of both functions. But in time of our trendy called web2.0 and ajax, JSON is the better solution. In some cases you might just throw the JSON data to the frontend of the user and process it via JavaScript.

Christian Weber


No comments yet

Post Comment

Everything? Send!

Spam Protection by WP-SpamFree