


Introduction 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
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:
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:
$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 < $max_index; $i ) {
$ str = serialize($array);
}
$end = xdebug_time_index();
echo $end - $start, '
';
echo 'json:
';
$start = xdebug_time_index();
for ($i = 0; $i < $max_index; $i ) {
$ str = json_encode($array);
}
$end = xdebug_time_index();
echo $end - $start, '
';
unset($array, $ str);
Output:
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:
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:
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.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The combination of golangWebSocket and JSON: realizing data transmission and parsing In modern Web development, real-time data transmission is becoming more and more important. WebSocket is a protocol used to achieve two-way communication. Unlike the traditional HTTP request-response model, WebSocket allows the server to actively push data to the client. JSON (JavaScriptObjectNotation) is a lightweight format for data exchange that is concise and easy to read.

Performance optimization methods for converting PHP arrays to JSON include: using JSON extensions and the json_encode() function; adding the JSON_UNESCAPED_UNICODE option to avoid character escaping; using buffers to improve loop encoding performance; caching JSON encoding results; and considering using a third-party JSON encoding library.

MySQL5.7 and MySQL8.0 are two different MySQL database versions. There are some main differences between them: Performance improvements: MySQL8.0 has some performance improvements compared to MySQL5.7. These include better query optimizers, more efficient query execution plan generation, better indexing algorithms and parallel queries, etc. These improvements can improve query performance and overall system performance. JSON support: MySQL 8.0 introduces native support for JSON data type, including storage, query and indexing of JSON data. This makes processing and manipulating JSON data in MySQL more convenient and efficient. Transaction features: MySQL8.0 introduces some new transaction features, such as atomic

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic

Quick Start: Pandas method of reading JSON files, specific code examples are required Introduction: In the field of data analysis and data science, Pandas is one of the important Python libraries. It provides rich functions and flexible data structures, and can easily process and analyze various data. In practical applications, we often encounter situations where we need to read JSON files. This article will introduce how to use Pandas to read JSON files, and attach specific code examples. 1. Installation of Pandas

In-depth understanding of PHP: Implementation method of converting JSONUnicode to Chinese During development, we often encounter situations where we need to process JSON data, and Unicode encoding in JSON will cause us some problems in some scenarios, especially when Unicode needs to be converted When encoding is converted to Chinese characters. In PHP, there are some methods that can help us achieve this conversion process. A common method will be introduced below and specific code examples will be provided. First, let us first understand the Un in JSON

The impact of serialization on Java performance: The serialization process relies on reflection, which will significantly affect performance. Serialization requires the creation of a byte stream to store object data, resulting in memory allocation and processing costs. Serializing large objects consumes a lot of memory and time. Serialized objects increase load when transmitted over the network.

C++ Library Serialization and Deserialization Guide Serialization: Creating an output stream and converting it to an archive format. Serialize objects into archive. Deserialization: Creates an input stream and restores it from archive format. Deserialize objects from the archive. Practical example: Serialization: Creating an output stream. Create an archive object. Create and serialize objects into the archive. Deserialization: Create an input stream. Create an archive object. Create objects and deserialize them from the archive.
