内容简介:在最新的4.5.6开发分支中,底层增加了2个特殊的函数: swoole_substr_json_decode swoole_substr_unserialize 这里为什么要增加这两个函数呢?有这样一种场景。使用Swoole\Server实现RPC服务,在EOF协议或长度协议...
在最新的4.5.6开发分支中,底层增加了2个特殊的函数:
swoole_substr_json_decodeswoole_substr_unserialize
这里为什么要增加这两个函数呢?有这样一种场景。使用Swoole\Server实现RPC服务,在EOF协议或长度协议通信方式下,一个包可能有3部分组成。
$packet = $header + $body + $footer
通常$header和$footer比较小,而$body比较大,$body可能会使用JSON或PHP序列化格式。如果要解析$body数据,那么就需要先进行substr得到$body的字符串格式数据,再进行json_decode和unserialize操作。
这会引起一次内存拷贝,$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_unserialize与substr + 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
以上所述就是小编给大家介绍的《Swoole 4.5.6 支持零拷贝 JSON 或 PHP 反序列化》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Spring Into HTML and CSS
Molly E. Holzschlag / Addison-Wesley Professional / 2005-5-2 / USD 34.99
The fastest route to true HTML/CSS mastery! Need to build a web site? Or update one? Or just create some effective new web content? Maybe you just need to update your skills, do the job better. Welco......一起来看看 《Spring Into HTML and CSS》 这本书的介绍吧!