Home >Web Front-end >JS Tutorial >Introduction to serialization and json usage in php_javascript skills

Introduction to serialization and json usage in php_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:29:311150browse

[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 < $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:

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