Swoole 4.5.6 supports zero copy JSON or PHP deserialization


In the latest4.5.6In the development branch, the bottom layer has been added2Special functions:

  • swoole_substr_json_decode
  • swoole_substr_unserialize

Why add these two functions here? There is such a scene. useSwoole\ServerrealizationRPCService, inEOFIn protocol or length protocol communication mode, a packet may have3Part composition.

$packet = $header + $body + $footer

usually$headerand$footerRelatively small, and$bodyRelatively large,$bodyMay useJSONorPHPSerialization format. If you want to parse$bodyData, then we need to do it firstsubstrobtain$bodyThe string format data ofjson_decodeandunserializeOperation.

This causes a copy of memory,$body_str = substr($packet, $header_length)A temporary string variable is created and then deserialized$body = json_decode($body_str)After that, the variable is released.

//First, substr is performed, and then the memory copy will be generated, and the data will be copied from $packet to $body_ Str
$body_str = substr($packet, 4, strlen($packet) - 4 - 2);
//After deserialization $body_ STR memory is no longer used and will be released when the function exits
$body = json_decode($body_str, true);

Using the two new functions, you cansubstrandDeserializationThe operation is combined into one. Reduce one copy of memory to improve performance.

$body = swoole_substr_json_decode($packet, $header_length);
$body = swoole_substr_unserialize($packet, $header_length);

Pressure measurement


$a['hello'] = base64_encode(random_bytes(1000));
$a['world'] = 'hello';
$a['int'] = rand(1, 999999);
$a['list'] = ['a,', 'b', 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'];

$val = serialize($a);
$str = pack('N', strlen($val)).$val."\r\n";

$n = 100000;

$s = microtime(true);
while($n--) {
    $l = strlen($str) - 6;
    // var_dump(unserialize(substr($str, 4, $l)));
    var_dump(swoole_substr_unserialize($str, 4, $l));
echo "cost: ".(microtime(true)-$s)."n";

useswoole_substr_unserializeAndsubstr + unserializeCompared with, the performance is improved12%

[email protected]:~/workspace/debug$ php s.php
cost: 2.2559139728546
[email protected]:~/workspace/debug$ php s.php
cost: 1.9821600914001

Swoole 4.5.6 supports zero copy JSON or PHP deserialization

Recommended Today

Introduction to vernacular spring cloud

First of all, let me show you a picture. If you don’t understand this picture very well, I hope you will suddenly realize it after reading my article. What is spring cloud Building a distributed system doesn’t need to be complex and error prone. Spring cloud provides a simple and easy to accept programming model […]