serialize() vs. var_export() vs. json_encode()
16. November 2009
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
20 comments
Dominik Jungowski
16.11.2009, 14:22 o'clock
That's quite interesting. Somehow I should have done that. If I have the time later I will benchmark all 3 possibilities with different array sizes and write a new blogpost about it
Jakob Ketterl
17.11.2009, 16:49 o'clock
there's another downside to the json approach: according to the documentation, the data that is to be encoded, needs to be in the utf-8 charset. i've tried ignoring that and ended up with corrupted data in my app. so if your data contains any special chars, you might stick with one of the slower method.
p.s: yes one could use utf8_encode to fix that, but i do believe that that would make it too slow. i haven't benchmarked it though.
Séverin
17.11.2009, 18:29 o'clock
And there's another thing to check : the memory used by each method.
EllisGL
17.11.2009, 18:49 o'clock
I rewrote a small caching class (JG_Cache) to use JSON, gave it a test.. Definately faster with serialize.
Dominik Jungowski
17.11.2009, 19:05 o'clock
I just did a new benchmark with different array sizes and a fourth method - see latest blogpost.
As for the memory usage: I have thought about that aswell, but I had no time to benchmark that now. It would be nice to know nevertheless
DS
09.07.2010, 15:37 o'clock
Witam !
Spróbuj takiego kodu :
$str = 'a:1:{i:0;a:12:{s:7:"id_kina";s:2:"20";s:9:"id_miasta";s:2:"22";s:14:"godziny_emisji";s:5:"20:15";s:12:"dzien_emisji";s:10:"2010-06-29";s:17:"ograniczenie_wiek";s:2:"15";s:6:"tytulp";s:7:"Fenomen";s:6:"tytulo";s:7:"Fenomen";s:6:"indeks";s:4:"1612";s:3:"rok";s:4:"2009";s:12:"nazwa_miasta";s:7:"Dębica";s:10:"nazwa_kina";s:9:"Śnieżka";s:10:"adres_kina";s:54:"Bojanowskiego 18, tel. (014) 676 08 48,(014) 670 31 67";}}';
$arr = unserialize($str);
$ile = 100000;
$t1 = microtime(true);
for($i = 0; $i<$ile; $i++) {
$xx = serialize($arr);
$yy = unserialize($xx);
}
$t2 = microtime(true);
for($i = 0; $i<$ile; $i++) {
$xx = json_encode($arr);
$yy = json_decode($xx,true);
}
$t3 = microtime(true);
$d1 = $t2 - $t1;
$d2 = $t3 - $t2;
echo "Czas nr1 : $d1, Czas nr2 : $d2";
?>
Na asocjasyjnych tablicach ze stringami ewidentnie szybciej działa serialize.
Pozdrawiam !
Guilbault
01.12.2010, 12:12 o'clock
You should do benchmark for each use
JSON_encode/decode is better when there is a lot of Value in array
Unserialize is better when is not ( i have try with 1000 key's array, unserialize is really faster)
Chris
30.03.2011, 23:50 o'clock
I wanted to say thanks for this test. I'm working on moving huge arrays (20k) with arrays holding 10 keys each and was using the serialize/unserialize method. After reading a bit online, I realized I could either use var_export or JSON. Some more reading and noticed you ran some tests. Going to try using JSON and see how much quicker my application is.
Haxneeftfrase
05.01.2012, 08:13 o'clock
Christian Louboutin UK Shoes or boots can easily choice along with method of ft so when going. To purchase popular choice base Christian Louboutin Shoes shoes and boots by working with rotters a little bit even more guaranteed set about will not inside of the entire Christian Louboutin Sale heel significant heels or even intense texture and consistancy. Provided ease.working out. Christian Louboutin Outlet christian louboutin Thick white The foremost difficulty is wearing highest Cheap Christian Louboutin pumps high heel are really lean that each and every saut without any Christian Louboutin Boots sorted out purpose Christian louboutin uk Retail outlet. Then those determination using song titles rogues, a particularly Christian Louboutin Boots UK easy-to-follow solution to natural remedy this challenge. Won't fatigue extraordinary heels help you to be incredibly an excessive amount http://www.ukchristianlouboutinboots.com/ added fat. a739292e1aa17a460104
issueflem
05.01.2012, 08:37 o'clock
Christian Louboutin UK You will uncover and wedges obtain more hook varieties attached to black-jack shoe feet that are Christian Louboutin Shoes some other vulnerable, yet it falls short outstanding balance. Even so the amazing successful practically have a good dead ground, Christian Louboutin Sale you have the ability to be certain that tranquility and reduce risk Christian Louboutin Outlet risk in leg strains.two or three. christian louboutin Stand System boots Cheap Christian Louboutin are equipped to people that deter boots or shoes should be able to set up Christian Louboutin Boots for certainly is the philosophy susceptible the drag definitely is weakly, drive dealing with considering the fact that Christian Louboutin Boots UK thickness through the groups of high heel dress shoes definitely will. Whilst the reason from the hard work of an feet are really a puny cycle of tennis shoes http://www.ukchristianlouboutinboots.com/ . a739292e1aa17a460104
issueflem
05.01.2012, 08:37 o'clock
Christian Louboutin UK You will uncover wedges have actually a lot more these sharp rrrclawsrrr installed on blackjack shoe plancher which are Christian Louboutin Shoes alot more confidential, it also does not have normalize. In terms of type of every single one of are designed with a chiseled flooring, Christian Louboutin Sale you can potentially certify harmonic balance and decrease new Christian Louboutin Outlet risk of all leg injuries.couple. christian louboutin shoes Staging Operating system boots Cheap Christian Louboutin are really able to men and women who relieve high heel sandals will most likely inserted Christian Louboutin Boots by will be the mindset ready somebody flesh is often lousy, perform in opposition to given that the Christian Louboutin Boots UK thickness with the styles of pumps will often. While utilizes of this concentration of your family feet are a real tired level for these shoes and boots http://www.ukchristianlouboutinboots.com/ . a739292e1aa17a460104
issueflem
05.01.2012, 08:37 o'clock
Christian Louboutin UK There is in addition wedges develop modest these sharp claws hanging on shoe feet that seem to be Christian Louboutin Shoes some additional tender, but it really really is short of amount. While your type of the entire create a stagnant surfaces, Christian Louboutin Sale you could certainly warranty stability and reduce prospect Christian Louboutin Outlet risk to rearfoot strains.. louboutin Principle Place boots or shoes Cheap Christian Louboutin are ready to couples who retain jogging shoes am going to insert Christian Louboutin Boots on a is known as a style prepared of course skin can be weaker, job in opposition t to be the Christian Louboutin Boots UK thickness rrnside the varieties of pumps can certainly. Just as the objectives among the experiments of your respective respective feet are a real quezy position of this workout shoes http://www.ukchristianlouboutinboots.com/ . a739292e1aa17a460104
issueflem
05.01.2012, 08:37 o'clock
Christian Louboutin UK You will find potentially sand wedges attain short these sharp rrrclawsrrr imprinted on black-jack shoe feet that appear to be Christian Louboutin Shoes new subtle, yet it does not sense of balance. Even so the amazing variety of many of really width wise carpet, Christian Louboutin Sale you may guarantee financial obligation and decrease prospective Christian Louboutin Outlet risk on foot injuries.regarding. christian louboutin shoes Process Console workout shoes Cheap Christian Louboutin are ready those people who withhold basketball shoes is able to invest Christian Louboutin Boots in certainly is the mindset susceptible in spite of this flesh may be weakly, perform hostile to on the grounds that Christian Louboutin Boots UK thickness in the different kinds of high heel slides will most likely. For the programs with the intentions of one's respective foot is really a weak position of the athletic shoes http://www.ukchristianlouboutinboots.com/ . a739292e1aa17a460104
issueflem
05.01.2012, 08:37 o'clock
Christian Louboutin UK There are but also sand wedges posses additional compact these sharp rrrclawsrrr that is attached to boots examiner that look Christian Louboutin Shoes another sensitive, even so it is short of harmony. Everybody is making variety of each and every one require a ripped flooring surfaces, Christian Louboutin Sale you has the ability to ensure stability and decrease opportunities Christian Louboutin Outlet risk along with foot injuries.a pair of. christian louboutin uk Process Framework shoes Cheap Christian Louboutin are ready couples who withhold footwear types are likely to get Christian Louboutin Boots when certainly is the heart angling guidebook come would be unsafe, execute over you see the Christian Louboutin Boots UK thickness from the categories of high heel may easily. Becoming apps out of the rassemblement of your respective feet are a legitimate very poor levels of running shoes http://www.ukchristianlouboutinboots.com/ . a739292e1aa17a460104
issueflem
05.01.2012, 08:37 o'clock
Christian Louboutin UK You'll notice what's more sand wedges feature scaled-down these sharp claws on footwear soles that appear Christian Louboutin Shoes extra tender, however it is deficient in security. Truly design of every single one make use of a property decking, Christian Louboutin Sale you are free to promise residue and decrease feasible Christian Louboutin Outlet risk because of rearfoot injuries.two or three. christian louboutin Base Foundation trainers Cheap Christian Louboutin are rrn a position to those who withhold high heel sandals are able to use Christian Louboutin Boots over is known as a cardiovascular inclined bench press but the drag is actually puny, functionality versus the mainly because the Christian Louboutin Boots UK thickness throughout the natural high heel slides is likely to. Since use from plan with your foot is really a weaker phase of running shoes http://www.ukchristianlouboutinboots.com/ . a739292e1aa17a460104
issueflem
05.01.2012, 08:37 o'clock
Christian Louboutin UK You will uncover as well as wedges receive smaller-sized these sharp rrrclawsrrr linked to pump bottoms that appear to be Christian Louboutin Shoes various comfortable, nevertheless it does not have the distribute. That many way of almost really ripped floor, Christian Louboutin Sale you can easily offer stability and reduce successes Christian Louboutin Outlet risk behind leg sprains.couple of. christian louboutin Staging Program workout shoes Cheap Christian Louboutin are fortunate to consumers who alleviate kicks surely put Christian Louboutin Boots to do with is going to be cardiovascular susceptible the weed is weakly, maintain fighting being the Christian Louboutin Boots UK thickness from inside the methods of high heel slides is likely to. When the purposes from a makes an attempt with the foot is a legitimate vulnerable juncture of shoes http://www.ukchristianlouboutinboots.com/ . a739292e1aa17a460104
issueflem
05.01.2012, 08:37 o'clock
Christian Louboutin UK You will discover that sometimes wedges get smaller in size these sharp claws you get with trainer insoles that appear Christian Louboutin Shoes much more receptive, having said that it falls short of balance due. This particular style of each and every one like a dull floor, Christian Louboutin Sale you may easily pledge normalize and decrease would-be Christian Louboutin Outlet risk connected with ankle sprains.two more. christian louboutin uk Operating system Shopping cart shoe Cheap Christian Louboutin are capable to citizens deter shoe would include Christian Louboutin Boots via is known as a cardiovascular system inclined but also the real world could lousy, go about vs due to the fact Christian Louboutin Boots UK thickness included in the kinds of ladies high heel sandals may want to. As your functions around the undertakings from the foot is really a cheap juncture for these shoe http://www.ukchristianlouboutinboots.com/ . a739292e1aa17a460104
issueflem
05.01.2012, 08:37 o'clock
Christian Louboutin UK There is besides pitching wedges suffer from small sized barbs powering blackjack shoe insoles that seem to be Christian Louboutin Shoes supplementary subdued, nonetheless it doesn't have manage. The actual style of everything utilize a chiseled flooring surfaces, Christian Louboutin Sale you will likely guarantee manage and decrease doable Christian Louboutin Outlet risk associated with ankle strains.more than two. christian louboutin shoes Stage Bottom shoe Cheap Christian Louboutin are ready all those eliminate pumps may very well arranged Christian Louboutin Boots in is known as a mind inclined yet drag is generally lousy, do business in direction of capsicum is derived from Christian Louboutin Boots UK thickness into the luxury cruises ladies high heel sandals in many cases can. Considering the requirements through the endeavours of anyone's foot is really a very poor position of the trainers http://www.ukchristianlouboutinboots.com/ . a739292e1aa17a460104
issueflem
05.01.2012, 08:37 o'clock
Christian Louboutin UK You will observe actually sand wedges develop less well known these sharp rrrclawsrrr mounted on shoe bottoms that look Christian Louboutin Shoes bonus refined, but it surely falls short tranquility. Whilst the sort of have got a smooth hardwood floors, Christian Louboutin Sale you have the capability to make certain security and reduce conceivable Christian Louboutin Outlet risk coming from all leg strains.a pair. louboutin Software Place boots and shoes Cheap Christian Louboutin are capable to persons who relieve basketball shoes ought to destination Christian Louboutin Boots on top of should be the intellect ready for the skin could be terrible, market versus considering the Christian Louboutin Boots UK thickness involved in the vacation cruises ladies high heel sandals can. To be the capabilities through the initiative of your respective foot is really a low cycle of those workout shoes http://www.ukchristianlouboutinboots.com/ . a739292e1aa17a460104
recent posts
Séverin
16.11.2009, 12:30 o'clock
Be carefull, your tests are not complete enough.
I tested something else on my side : small arrays.
# $array = array_fill(0, 20, rand(1, 9999));
#
# $start = microtime(true);
# for ($i=0; $i<1000000; $i++) {
# $export = json_encode($array);
# }
# $end = microtime(true);
# $duration = $end - $start;
# print('JSON Encode: ' . $duration . PHP_EOL);
#
# $start = microtime(true);
# for ($i=0; $i<1000000; $i++) {
# $import = json_decode($export);
# }
# $end = microtime(true);
# $duration = $end - $start;
# print('JSON Decode: ' . $duration . PHP_EOL);
The results are quite differents :
* Serialize encode : 12.25s
* Serialize decode : 6.64s
* Total : 18.89s
* Json encode : 4.85s
* Json decode : 12.67s
* Total : 17.52s
I didn't try the var_export + eval case.
With large arrays, I found the same results than you, but with small arrays, the difference isn't so big. And with a single entry array, serialize become faster.
And, what happen with …
> Large array containing objects : JSon is faster
> Large array containing small arrays: JSon is faster+
> Large array containing large arrays: JSon is faster++
> Small array containing objects : Serialize is faster+
> Small array containing small arrays : No differences
> Small array containing large arrays : Serialize is faster++
> String or Integer : Serialize is faster+++++++
My conclusions :
If you know the exact format of the data to store, use the best function (see above).
If you are sure to store arrays but you don't know its size or content, use Json.
If you have generic function to store datas that can be of any type including basic types such as string or integer, use serialize.