serialize() vs. var_export() vs. json_encode()

Permanent Link: serialize() vs. var_export() vs. json_encode() 16. November 2009 RSS Feed for comments on RSS-Feed für Kommentare zu: serialize() vs. var_export() vs. json_encode() comments feed

There are times when you need to store an array, for example when your array is an index you wanna use again the next time you run your application. In order to store an array you have to transform it into some kind of string represantation first, most people would probably use serialize(). But there are also 2 other ways to achieve that: var_export() and json_encode().

After having them stored the functions to interpret the strings as arrays would be unserialize() if you use serialize(), eval() if you use var_export() and json_decode() if you use json_encode().

So, what about the performance?

In order to test that I wrote a little profiling script that first created some random array with 1.000.000 elements, then exported the array and then imported it again. For the json_encode() test the script looked like that:

$array = array_fill(0, 1000000, rand(1, 9999));

$start = microtime(true);
$export = json_encode($array);
$end = microtime(true);
$duration = $end - $start;
print('JSON Encode: ' . $duration . PHP_EOL);

$start = microtime(true);
$import = json_decode($export);
$end = microtime(true);
$duration = $end - $start;
print('JSON Decode: ' . $duration . PHP_EOL);

Apart from the exporting and importing functions used, the script for serialize() and var_export() looked pretty much the sime, var_export() being the only exception, since I had to add an ending ; to $export in order for it to work with eval().

While it is understandable that importing takes longer for every method than importing, the differences in time are quite astounding:

It's not only interesting to see that unserialize() is damn slow but also that JSON is fastest, which also gets quite clear when looking at combined results:


Since it's still in the Ubuntu repositories, I did the performance tests with PHP 5.2.6


twitters Gravatar

30.08.2013, 20:25 o'clock

Thank you for this json unserialize comparison.

MURATs Gravatar

10.08.2014, 18:06 o'clock

It is useful for me. Thank you for posting

moyva1818s Gravatar

15.11.2014, 16:11 o'clock

F Review mobicool s32 X
M Buy cheap nolvadex no prescription X
C Side effects of coming off neurontin A
L Prilosec otc price X D Off label uses for buspar W
Z Amoxil for sale A O Arimidex to get rid of bloat W
Z Where to get singulair B

Write a comment

(will not be published)