Skip to content

Instantly share code, notes, and snippets.

@developersharif
Last active April 19, 2023 08:25
Show Gist options
  • Save developersharif/a2453414ae45c08998baec1955adf86e to your computer and use it in GitHub Desktop.
Save developersharif/a2453414ae45c08998baec1955adf86e to your computer and use it in GitHub Desktop.
PHP Vs Nodejs Benchmark
const mysql = require('mysql2/promise');
const http = require('http');
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: '',
database: 'nobarun',
waitForConnections: true,
connectionLimit: 10,
});
http.createServer(async (req, res) => {
const path = req.url;
if (path === '/') {
try {
const conn = await pool.getConnection();
const [rows] = await conn.query('SELECT * FROM users');
let responseBody = '';
rows.forEach(row => {
responseBody += `${row.name} ${row.role}<br>`;
});
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(responseBody);
conn.release();
} catch (err) {
res.writeHead(500, {'Content-Type': 'text/html'});
res.end(`<h1>An error occurred</h1><p>${err.message}</p>`);
}
} else if (path === '/about') {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('This is the about page.');
} else {
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('Page not found.');
}
}).listen(5000);
console.log('Server started at http://localhost:5000');
const express = require('express');
const app = express();
const mysql = require('mysql');
const connection = mysql.createConnection({
host: '127.0.0.1',
user: 'root',
password: '',
database: 'nobarun'
});
connection.connect((err) => {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
app.get('/', (req, res) => {
connection.query('SELECT * FROM users', (error, results) => {
if (error) {
res.status(500).send("<h1>An error occurred</h1><p>" + error + "</p>");
return;
}
let responseBody = '';
for (let i = 0; i < results.length; i++) {
responseBody += results[i].name + ' ' + results[i].role + '<br>';
}
res.send(responseBody);
});
});
app.get('/about', (req, res) => {
res.type('text/plain');
res.send('This is the about page.');
});
app.use((req, res) => {
res.type('text/plain');
res.status(404);
res.send('Page not found.');
});
const server = app.listen(5000, () => {
console.log('Server started at http://localhost:5000');
});
//run node server.js
<?php
use Swoole\Coroutine\Channel;
use Swoole\Http\Request;
use Swoole\Http\Response;
use Swoole\Http\Server;
$pool = new Channel(10);
$server = new Server("0.0.0.0", 4173);
$server->on("WorkerStart", function () use ($pool) {
// MySQL server configuration
$host = '127.0.0.1';
$username = 'root';
$password = '';
$dbname = 'nobarun';
// Create a new MySQLi object
$mysqli = new mysqli($host, $username, $password, $dbname);
// Check connection
if ($mysqli->connect_errno) {
throw new Exception("Failed to connect to MySQL: " . $mysqli->connect_error);
}
// Add the connection to the pool
$pool->push($mysqli);
});
$server->on("request", function (Request $request, Response $response) use ($pool) {
// Get the request path
$path = $request->server['request_uri'];
// Handle the route based on the path
if ($path == '/') {
$response->header("Content-Type", "text/html; charset=utf-8");
try {
// Get a connection from the pool
$mysqli = $pool->pop();
// Query the database
$sql = "SELECT * FROM users";
$result = $mysqli->query($sql);
// Loop through the result set
$responseBody = '';
while ($row = $result->fetch_assoc()) {
$responseBody .= $row['name'] . ' ' . $row['role'] . '<br>';
}
// Release the connection back to the pool
$pool->push($mysqli);
// Send the response
$response->end($responseBody);
} catch (Exception $e) {
$response->header("Content-Type", "text/html; charset=utf-8");
$response->status(500);
$response->end("<h1>An error occurred</h1><p>" . $e->getMessage() . "</p>");
}
} else if ($path == '/about') {
$response->header("Content-Type", "text/plain");
$response->end("This is the about page.");
} else {
$response->header("Content-Type", "text/plain");
$response->status(404);
$response->end("Page not found.");
}
});
echo "Server started at http://localhost:4173\n";
$server->start();
//run php server.php
@developersharif
Copy link
Author

developersharif commented Apr 19, 2023

Screenshot from 2023-04-19 14-19-48
bash sharif@linux:~/Documents/Codes/php/swoole$ wrk -t12 -c400 -d10s http://127.0.0.1:5000
Running 10s test @ http://127.0.0.1:5000
12 threads and 400 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 76.12ms 11.30ms 155.02ms 88.53%
Req/Sec 432.52 97.49 666.00 70.23%
51706 requests in 10.07s, 15.78MB read
Requests/sec: 5132.19
Transfer/sec: 1.57MB
bash sharif@linux:~/Documents/Codes/php/swoole$ wrk -t12 -c400 -d10s http://127.0.0.1:4173
Running 10s test @ http://127.0.0.1:4173
12 threads and 400 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 9.02ms 2.20ms 46.12ms 91.19%
Req/Sec 3.63k 516.06 11.55k 96.36%
435966 requests in 10.09s, 96.46MB read
Requests/sec: 43187.51
Transfer/sec: 9.56MB

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment