Introduction to serialization and JSON usage in PHP

Source: Internet
Author: User
Tags comparison json serialization strlen

"The concept of serialization"

Serialization is the process of converting an object's state into a format that can be persisted or transmitted. The opposite of serialization is deserialization, which converts a stream to an object. These two processes combine to make it easy to store and transfer data.

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

Typically, all the fields of an object instance are serialized, which means that the data is represented as the serialized data of the instance. In this way, the code that interprets the format might be able to determine the value of the data without relying on the accessibility of that member. Similarly, deserialization extracts data from a serialized representation and sets the object state directly, regardless of accessibility rules. If possible, you should make the object not serializable for any object that might contain important security data. If it must be serializable, try to generate a specific field to hold important data that is not serializable. If this is not possible, you should be aware that the data is exposed to any code that has serialization permissions, and that no malicious code is allowed to get that permission.

"The concept of JSON"

Json,javascript Object notation, a lighter, friendlier format for interface (AJAX, rest, etc.) data interchange. JSON is a text format for structured data serialization, as an alternative to XML that represents the format of the data exchange payload between clients and servers. It derives from the ECMAScript language standard. The goal of JSON is to make it small, lightweight, text, and a subset of JavaScript.

"Comparison of length"

The following code shows the string and its length that are generated by the array and object encoding

Copy Code code 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 <br/> ';
}

public static function output ($STR) {
echo $str, ' <br/> ';
}

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 (' JSON value: '. $json _str. "; Length= ". strlen ($json _str));
}

}

$test _data = Array (' wwww ' => 0, ' Phppan ' => 1, ' com ' => 2);
Serializing an array of

Echo ' array: <br/> ';
Foo::compare_serialize_and_json ($test _data);

$foo = new Foo ();
Echo ' object: <br/> ';
Foo::compare_serialize_and_json ($foo);

Output:

Copy Code code as follows:


array:


Serialization 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


JSON value: {"int": 1, "bool": TRUE, "array": {"0": [1], "2": "Test", "3": "String"}}; length=63

The obvious length difference is that serialize is about twice times the size of JSON after encoding.

Reason:

After serialize the string contains the length of the substring, which may be an optimization of the speed, the typical space to change time, but it is still too heavy.
Serialize has more detailed type distinctions, and JSON has only four types, and is represented by a simple notation.

"Comparison of Speed"

To illustrate the problem in code, compare the speed code as follows:

Copy Code code as follows:


$max _index = 10;


ini_set ("Memory_limit", "512M");


$array = Array_fill (0, 1000000, rand (1, 9999));

echo ' serialize:<br/> ';
$start = Xdebug_time_index ();
for ($i = 0; $i < $max _index; $i + +) {
$str = serialize ($array);
}
$end = Xdebug_time_index ();
Echo $end-$start, ' <br/> ';

echo ' json:<br/> ';
$start = Xdebug_time_index ();
for ($i = 0; $i < $max _index; $i + +) {
$str = Json_encode ($array);
}
$end = Xdebug_time_index ();
Echo $end-$start, ' <br/> ';
Unset ($array, $STR);

Output:

Copy Code code as follows:


Serialize:


9.5371007919312


JSON:


1.4313209056854

The serialize speed is one order of magnitude faster than JSON in the case of large data volumes.

From the above two points, JSON is better than serialize in terms of speed or the size of the generated string, so why does serialize still exist? The reason is the following: the functionality of the implementation.

"Process Objects"

The following code:

Copy Code code as follows:


header ("Content-type:text/html;charset=utf8");


class Foo {


Public Function test ($flag) {


echo $flag, ' test function for Foo &lt;br/&gt; ';


    }


}

$foo = new Foo ();

echo ' deserialization test: <br/> ';
$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 code as follows:


anti-serialization 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"

• Serialization uses serialize, especially the storage of objects. This is the meaning of its existence.
• Data stores that are not object-independent can use JSON, such as arrays that contain a large number of numbers. Just when it comes to this, what we need to do is probably refactor the database.
• Use JSON for data interchange, which is also where it is defined.
• Currently JSON is the data that can be used for UTF-8 encoding.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.