Asked 7 years ago
28 Dec 2016
Views 2098

posted

serialize() vs json_encode()

serialize() or json_encode() which one is better to use ? as considering performance and memory usage . which one is good and why ?

i am using serialize() or json_encode() both as per requirement but now i want to stick with one which help me to give better performance in php so suggest
serialize() and json_encode() are same. - noob  
Dec 28 '16 23:54
noob

noob
answered Nov 30 '-1 00:00

serialize() and json_encode() are same . so there is no serialize() vs json_encode()
serialize() and json_encode() both transform array or object to single string which easy to re transformation to array or object.so serialize() and json_encode() have same use which is easy transport or store of complex structure or object or array .
Mitul Dabhi

Mitul Dabhi
answered Nov 30 '-1 00:00

1. execution speed serialize() vs json_encode()

serialize() is slower than json_encode() as compare to execution, serialize() take more time to execute than json_encode

so score is json_encode() :: 1 and serialize() :: 0

2. memory usage
serialize() is use more execution memory as compare to json_encode()

so score is json_encode() :: 2 and serialize() :: 0

3. ease of use

 $student=array(array("name"=>"sam","roll_no"=>10,"semester"=>3),
 array("name"=>"jaddy","roll_no"=>11,"semester"=>3) ,
 array("name"=>"garg","roll_no"=>12,"semester"=>3)
 );
echo $data= serialize($student)."<br/>"; 
echo $data= json_encode($student);

serialize() return

a:3:{i:0;a:3:{s:4:"name";s:3:"sam";s:7:"roll_no";i:10;s:8:"semester";i:3;}i:1;a:3:{s:4:"name";s:5:"jaddy";s:7:"roll_no";i:11;s:8:"semester";i:3;}i:2;a:3:{s:4:"name";s:4:"garg";s:7:"roll_no";i:12;s:8:"semester";i:3;}}


json_encode() return

[{"name":"sam","roll_no":10,"semester":3},{"name":"jaddy","roll_no":11,"semester":3},{"name":"garg","roll_no":12,"semester":3}]


json_encode() returned value simply awesome and human friendly . so it is very easy to debug , analyze , compare and to use.

in ease of use json_encode() win again over serialize()

so score is json_encode() :: 3 and serialize() :: 0

4. storage wise performance

json_encode() returned string take less space to store in database / session / files as compare to serialize() ,

echo $data= strlen(serialize($student)) ; // 216
echo $data= strlen(json_encode($student)); // 127

its almost double space occupied by serialize() returned string

so score is json_encode() :: 4 and serialize() :: 0


so it is clean win of json_encode() over serialize() , one can use json_encode() without doubt over serialize()
Post Answer