Home >PHP Framework >Swoole >How swoole improves php performance
Network request handling in Swoole is event-based and takes full advantage of the underlying epoll/kqueue implementation, making it very easy to serve millions of requests.
Swoole4 uses a new coroutine kernel engine, and now it has a full-time development team, so we are entering an unprecedented period in PHP history, providing unique possibilities for rapid performance improvements. (Recommended learning: swoole video tutorial)
Coroutine
Swoole4 or higher has a built-in coroutine with high availability. You can use fully synchronous code to achieve asynchronous performance, the PHP code does not have any additional keywords, and coroutine scheduling is automatically performed under the hood.
Developers can understand coroutines as ultra-lightweight threads, and you can easily create thousands of coroutines in a process.
It only takes 0.2 seconds to read massive data from MySQL with 10,000 concurrent requests
$s = microtime(true); Co\run(function() { for ($c = 100; $c--;) { go(function () { $mysql = new Swoole\Coroutine\MySQL; $mysql->connect([ 'host' => '127.0.0.1', 'user' => 'root', 'password' => 'root', 'database' => 'test' ]); $statement = $mysql->prepare('SELECT * FROM `user`'); for ($n = 100; $n--;) { $result = $statement->execute(); assert(count($result) > 0); } }); } }); echo 'use ' . (microtime(true) - $s) . ' s';
Hybrid server
You can Create multiple services on an event loop: TCP, HTTP, Websocket and HTTP2, and can easily host tens of thousands of requests.
function tcp_pack(string $data): string { return pack('N', strlen($data)) . $data; } function tcp_unpack(string $data): string { return substr($data, 4, unpack('N', substr($data, 0, 4))[1]); } $tcp_options = [ 'open_length_check' => true, 'package_length_type' => 'N', 'package_length_offset' => 0, 'package_body_offset' => 4 ]; --------------------------------------------------------------------------------------------------------------- $server = new Swoole\WebSocket\Server('127.0.0.1', 9501, SWOOLE_BASE); $server->set(['open_http2_protocol' => true]); // http && http2 $server->on('request', function (Swoole\Http\Request $request, Swoole\Http\Response $response) { $response->end('Hello ' . $request->rawcontent()); }); // websocket $server->on('message', function (Swoole\WebSocket\Server $server, Swoole\WebSocket\Frame $frame) { $server->push($frame->fd, 'Hello ' . $frame->data); }); // tcp $tcp_server = $server->listen('127.0.0.1', 9502, SWOOLE_TCP); $tcp_server->set($tcp_options); $tcp_server->on('receive', function (Swoole\Server $server, int $fd, int $reactor_id, string $data) { $server->send($fd, tcp_pack('Hello ' . tcp_unpack($data))); }); $server->start();
The above is the detailed content of How swoole improves php performance. For more information, please follow other related articles on the PHP Chinese website!