search
HomeWeb Front-endJS TutorialIntroduction to serialization and json usage in php_javascript skills

[Concept of serialization]

Serialization is the process of converting object state into a persistable or transportable format. The opposite of serialization is deserialization, which converts a stream into an object. These two processes combine to easily store and transfer data.

The process of converting an object's state information into a form that can be stored or transmitted. During serialization, an object writes its current state to temporary or persistent storage. Later, the object can be recreated by reading or deserializing the object's state from the store.

Typically, all fields of an object instance are serialized, which means the data is represented as the instance's serialized data. This way, code that can interpret the format may be able to determine the value of this data without relying on the accessibility of the member. Similarly, deserialization extracts data from the serialized representation and sets object state directly, again regardless of accessibility rules. Any object that may contain important security data should be made non-serializable if possible. If it must be serializable, try to generate specific fields to hold important data that is not serializable. If this is not possible, you should be aware that the data will be exposed to any code with serialization permissions, and ensure that no malicious code gains that permission.

[JSON concept]

JSON, JavaScript Object Notation, a lighter and more friendly format for interface (AJAX, REST, etc.) data exchange. JSON is a text format for serializing structured data. As an alternative to XML, it is used to represent the payload of data exchange between clients and servers. It is derived from the ECMAScript language standard. The design goals of JSON are to make it small, lightweight, textual, and a subset of JavaScript.

【Comparison of lengths】

The following piece of code shows the string and its length generated after encoding arrays and objects

Copy code The code is as follows:

class Foo {

public $int = 1;
public $bool = TRUE;
public $array = array(array(1), 2 => 'test', 'string');

public function test($flag) {
echo $flag, 'test function for Foo
';
}

public static function output($str) {
echo $str, '
';
}

public static function compare_serialize_and_json($data) {
$serialize_str = serialize($data);
self::output('Serialized value:' . $serialize_str . "; length=" .
strlen($serialize_str));

$json_str = json_encode($data);
self::output('Value after JSON:' . $json_str . "; length=" . strlen($json_str));
}

}

$test_data = array('wwww' => 0, 'phppan' => 1, 'com' => 2);
//Serialized array

echo 'Array:
';
Foo::compare_serialize_and_json($test_data);

$foo = new Foo();
echo 'Object:
';
Foo::compare_serialize_and_json($foo);

Output:

Copy code The code is as follows:

Array:
Serialized value: a :3:{s:4:"wwww";i:0;s:6:"phppan";i:1;s:3:"com";i:2;}; length=52
JSON Value: {"wwww":0,"phppan":1,"com":2}; length=29
Object:
Serialized value:O:3:"Foo":3: {s:3:"int";i:1;s:4:"bool";b:1;s:5:"array";a:3:{i:0;
a:1:{ i:0;i:1;}i:2;s:4:"test";i:3;s:6:"string";}}; length=111
Value after JSON:{"int ":1,"bool":true,"array":{"0":[1],"2":"test","3":"string"}}; length=63

Obvious length difference, serialize is about twice as long as json after encoding.

Reason:

•After serializing, the string contains the length of the substring. This may be a speed optimization, a typical space-for-time, but it itself is still too heavy.
•Serialize has more detailed type distinctions, while json only has four types, and they are represented by simple symbols.

【Speed ​​comparison】

Illustrate the problem with code, the following code compares the speed:

Copy code The code is as follows:

$max_index = 10;
ini_set("memory_limit","512M");
$array = array_fill(0, 1000000, rand(1, 9999));

echo 'serialize:
';
$start = xdebug_time_index();
for ($i = 0; $i $ str = serialize($array);
}
$end = xdebug_time_index();
echo $end - $start, '
';

echo 'json:
';
$start = xdebug_time_index();
for ($i = 0; $i $ str = json_encode($array);
}
$end = xdebug_time_index();
echo $end - $start, '
';
unset($array, $ str);

Output:

Copy code The code is as follows:

serialize:
9.5371007919312
json:
1.4313209056854

The speed of serialize is an order of magnitude faster than json when the amount of data is large.

From the above two points, json is better than serialize in terms of speed and the size of the generated string, so why does serialize still exist? The reason lies in the following point: the implemented function.

【Processing object】

The following code:

Copy code The code is as follows:

header("Content-type: text/html;charset =utf8");
class Foo {
public function test($flag) {
echo $flag, 'test function for Foo
';
}
}

$foo = new Foo();

echo 'Deserialization test:
';
$foo->test(1);
$serialize_str = serialize($foo);
$obj = unserialize ($serialize_str);
$obj->test(2);

$foo->test(1);
$json_str = json_encode($foo);
$obj = json_decode($json_str);
$obj->test(2);
die();

Output:

Copy code The code is as follows:

Deserialization test:
1test function for Foo
2test function for Foo
1test function for Foo

( ! ) Fatal error: Call to undefined method stdClass::test()

json cannot handle data such as object methods.

【Scope of use】

•Use serialize for serialization, especially for object storage. This is the meaning of its existence.
•Json can be used for object-independent data storage, such as arrays containing large numbers, etc. But when encountering this situation, what we need to do may be to reconstruct the database.
•JSON is used for data exchange, which is where its definition lies.
•Currently JSON can be used for UTF-8 encoded data.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.