Swoole 4.5.6 支持零拷贝 JSON 或 PHP 反序列化

码农天地 -
Swoole 4.5.6 支持零拷贝 JSON 或 PHP 反序列化

在最新的4.5.6开发分支中,底层增加了2个特殊的函数:

swoole_substr_json_decodeswoole_substr_unserialize

这里为什么要增加这两个函数呢?有这样一种场景。使用Swoole\Server实现RPC服务,在EOF协议或长度协议通信方式下,一个包可能有3部分组成。

$packet = $header + $body + $footer

通常$header$footer比较小,而$body比较大,$body可能会使用JSONPHP序列化格式。如果要解析$body数据,那么就需要先进行substr得到$body的字符串格式数据,再进行json_decodeunserialize操作。

这会引起一次内存拷贝,$body_str = substr($packet, $header_length)的过程会创建一个临时字符串变量,再反序列化操作$body = json_decode($body_str)之后,这个变量就会被释放。

// 先进行 substr,这时会产生内存拷贝,从 $packet 复制数据到 $body_str
$body_str = substr($packet, 4, strlen($packet) - 4 - 2);
// 反序列化之后 $body_str 这块内存不再使用,会在函数退出时释放
$body = json_decode($body_str, true);

使用新增的两个函数就可以将substr反序列化操作合二为一。减少一次内存拷贝,从而提高性能。

$body = swoole_substr_json_decode($packet, $header_length);
$body = swoole_substr_unserialize($packet, $header_length);
压测
<?php
error_reporting(E_ALL);

$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."rn";

$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";

使用swoole_substr_unserializesubstr + unserialize相比,性能提升了12%

htf@htf-ThinkPad-T470p:~/workspace/debug$ php s.php
cost: 2.2559139728546
htf@htf-ThinkPad-T470p:~/workspace/debug$ php s.php
cost: 1.9821600914001

特别申明:本文内容来源网络,版权归原作者所有,如有侵权请立即与我们联系(cy198701067573@163.com),我们将及时处理。

php介绍

PHP即“超文本预处理器”,是一种通用开源脚本语言。PHP是在服务器端执行的脚本语言,与C语言类似,是常用的网站编程语言。PHP独特的语法混合了C、Java、Perl以及 PHP 自创的语法。利于学习,使用广泛,主要适用于Web开发领域。

Tags 标签

swoolephpjson

扩展阅读

加个好友,技术交流

1628738909466805.jpg