JSON or serialize: the eternal question of a PHP developer
\n\nImagine: you are writing a PHP script that needs to save a complex array with user settings. Two options immediately come to mind: json_encode() and serialize(). Which one to choose? This question torments thousands of developers on Stack Overflow, and today we will once and for all figure out which method is truly better.
I will show you not only dry comparisons, but also real code examples, performance tests, and pitfalls that the documentation doesn't mention. Let's go!
\n\nWhat do json_encode and serialize have in common?
\n\nBoth functions convert complex data structures (arrays, objects) into a string that can be saved to a file, database, or cache. But they do it differently.
\n\n- \n
- json_encode — converts data into a standard JSON format (text understandable to JavaScript and most languages). \n
- serialize — creates an internal PHP format that contains information about data types and can restore objects while preserving classes. \n
Simple code example
\n\n<?php\n$array = [\n 'name' => 'Ivan',\n 'age' => 30,\n 'skills' => ['PHP', 'JavaScript', 'Python']\n];\n\n// JSON\n$json = json_encode($array, JSON_UNESCAPED_UNICODE);\necho $json; // {"name":"Ivan","age":30,"skills":["PHP","JavaScript","Python"]}\n\n// Serialize\n$serialized = serialize($array);\necho $serialized; // a:3:{s:4:"name";s:8:"Ivan";s:3:"age";i:30;s:6:"skills";a:3:{i:0;s:3:"PHP";i:1;s:10:"JavaScript";i:2;s:6:"Python";}}\n?>\n\nThe difference is immediately visible: JSON is more compact and readable, while serialize is more verbose but contains more metadata.
\n\nComparison by key criteria
\n\nLet's break it all down. I ran tests and collected data that will help you make a decision.
\n\n1. Performance: which is faster?
\n\nMany think that serialize works faster because it is a "native" PHP format. But reality is more complex.
\n\n<?php\n$largeArray = [];\nfor ($i = 0; $i < 10000; $i++) {\n $largeArray[] = [\n 'id' => $i,\n 'name' => 'User_' . $i,\n 'data' => range(1, 50)\n ];\n}\n\n// Test json_encode\n$start = microtime(true);\n$json = json_encode($largeArray);\n$jsonTime = microtime(true) - $start;\n\n// Test serialize\n$start = microtime(true);\n$serialized = serialize($largeArray); \n$serializeTime = microtime(true) - $start;\n\necho "JSON: {$jsonTime} sec\\n";\necho "Serialize: {$serializeTime} sec\\n";\n// Result: JSON is often 10-30% faster\n?>\n\nConclusion: json_encode is usually faster, especially on large arrays. The reason is that JSON uses a simpler algorithm without saving class information.
2. Data size: which is more compact?
\n\nJSON almost always wins in size. Compare for yourself:
\n\n- \n
- JSON:
{"name":"Ivan","age":30}— 26 bytes \n - Serialize:
a:2:{s:4:"name";s:8:"Ivan";s:3:"age";i:30;}— 41 bytes \n
The difference is 1.5-2 times in favor of JSON. If you store gigabytes of data in a cache, this is critical.
\n\n3. Security: the hidden threat of serialize
\n\nThis is where many get caught. unserialize() can execute arbitrary code if you pass it tampered data. This is called PHP object injection.
<?php\n// Dangerous example\n$userInput = $_GET['data']; // User can pass a malicious string\n$object = unserialize($userInput); // Risk! Can create an object with dangerous code\n\n// Safe alternative\n$jsonData = json_decode($userInput, true); // Just an array, no objects\n?>\n\nImportant: Never use unserialize() with user-supplied data. JSON is absolutely