At times you might need to store an array in a session or database, to be used later by your application. You cant just store the array as is, so you have to convert it into a string representation of the array first. PHP offers a couple of ways to do this, however, most developers tend to use the serialize function to do the job. Alternately you can also use the json_encode function to convert your array. This post is going to focus on the performance difference between the two functions. For profiling, I used XHProf, and PHP 5.3.8, running on CentOS 5.4.
Building the array
To generate an array that we can convert, I am going to fill it with random values.
1 | $array = array_fill( 0, 100000, rand( 1000, 9999 ) ); |
The serialize function
We are then going to take the array and pass it to the serialize function
1 | $serial = serialize( $array ); |
The json_encode function
Take the array and convert it with json_encode
1 | $json = json_encode( $array ); |
The profiler results
Using XHProf, I profiled both function calls, keeping track of memory usage and execution time. I ran the same script 10 times to get an average.
serialize took an average of 60000 microseconds and 1,489,700 bytes to convert the array.
json_encode took an average of 11500 microseconds and 500,700 bytes to convert the array.
The difference in time and memory usage is quite big
But what about converting the string back to an array?
Surprisingly, I found json_decode to be a little bit slower than unserialize here.
To convert the serialized string, unserialze took an average of 38732 microseconds, and 14,649,900 bytes
To convert the json encoded string, json_decode took an average of 42000 microseconds, and 14,649,500 bytes
Here is an example of one profiling report
