json_encode/json_decode vs serialize/unserialize and fools vs idiots.

1249088491000 » Tagged as: JavaScript , religion , Wordpress

If you want to write good , fast, memory efficient code (pick any three) you need to start off with good fast memory efficient algorithms. Using fprintf instead of fwrite or  java.util.ArrayList instead of java.util.Vector or $.ajax instead of $.get doesn't really make any difference at all. If you spend your life trying to figure out which is faster or takes up less memory you will never get anything done. Sometimes people who ought to know better even shout from the rooftops that you should waste your time trying to shave off a few milliseconds here and there but fortunately there are more wiser heads to shoot them down.

Since PHP added support for JSON encode and decode a lot has been written about how it's more efficient than serialize / unserialize and the have got the numbers to proove it too. In one study it was pointed out that json_encode takes 0.63 milli seconds to convert a certain object to text while the serialize function took just 0.41 milliseconds however that author suggests that all existing code that uses serialize/unserialize should be changed to json_encode/json_decode because decode/unserialize more often than encode/serialize and json_decode takes just 1.42ms vs 2.28 ms for unserialize. Another mutt had reproduced the same sort of results on eight different servers. Sure that's about a 50% improvement in speed. And if your script just happens to be executed 1,000,000 times you will save a whopping 860 seconds! you will probably get a 100% increment at your next evaluation too.

Most often you want to convert and object to a string because you want to send it over the wire or save it in a database. If your applications appears to be slow it's probably because the database query is slow or it takes a lot of time to retrieve the data from the remote server. If it takes two seconds to retrieve/store  the data what difference does it make to shave of 0.0005 of a second by changing from json to php serialize?

I am not saying you should not make any effort to optimize your code at all. Wordpress and Windows OS are examples that scream out for optimization. What I am saying is that you should write your code with a decent algorithm (but don't rupture yourself looking for one), then test your app. If you find it's slow and doesn't scale well, run it through a profiler to find the bottleneck. You will usually find that about 20% of the code takes up about 80% of the execution time sometims it's worse. All you need to do is to look at that part of the code and optimize it or perhaps even change the algorithm.

comments powered by Disqus