PHP vs NodeJS Comparison and Benchmark

Almost every day there are some new technologies emerging, that are trying to change the web landscape. Server-side of the web development also is divided, there are long-standing heavy-weights such as Java, C, and Perl and newer, more web-focused languages like Ruby, Clojure and Go. But how to select a perfect solution for your project? We will compare two back-end technologies PHP vs NodeJS. We hope we won’t start a holy war.

First of all, let’s define PHP and Node.js.

PHP

PHP is a server-side scripting language. It was created in 1994 by Rasmus Lerdorf in 1994 primarily for web development. Originally PHP stood for Personal Home Page, but now it stands for a recursive acronym – PHP: Hypertext Preprocessor.  
Usually, PHP is processed by an interpreter, powered by the Zend Engine, that is installed on web servers such as Apache and Nginx. Also PHP code can be embedded into HTML or HTML5 markup. This flexibility contributed to the popularity of the language, PHP is now used on more than 80% of web servers.

Node.js

Node.js is an open-source, JavaScript run-time environment used to execute JavaScript code on the server-side. Node.js development process has changed the paradigm that JavaScript is used primarily on the client-side. That’s why Node.js has become one of the foundational elements of the “JavaScript everywhere” paradigm. Node.js was created by Ryan Dahl in 2009. It is powered by Google’s V8 JS engine, that is the same engine that is used in Google Chrome web browser. This JS runtime environment doesn’t need a separate web server or other dependencies, there are built-in libraries that take care of that. Compared to PHP, Node.js is relatively young, however, it is already well recognized and used by giant companies like Microsoft, Yahoo, LinkedIn, and PayPal.

 

For a clearer view, here is the PHP vs NodeJS comparison of the popularity indicators in the form of a table:

PHP Node JS
Release date 08.06.1995 27.05.2009
Package’s repository (Dependency Manager) Composer NPM
Have LTS? + +
License (Free for commercial use) PHP License MIT License
Vacancies/ Developers ~100 000/4000000 60000/*
Packages  on packagist/ npm 152 453 ~450,000
Open-source projects 290,757 114,353
Questions on stackoverflow 1,112,866 187,917
GitHub stars 12 670 38 398
Contributors 485 1488
Most popular conferences of 2016 Laracon EU 2016
SymfonyCon Berlin 2016
Ski PHP Conference 2016
PHPBenelux Conference 2016
SunshinePHP 2016
The PHP UK Conference
JSConf
Fluent
dotJS
FullStack
ForwardJS
JSFoo
Documentation (php.net) (nodejs.org)
Certification Zend
Symfony official certification
Node.js Certification Program

Features and Benefits of PHP and NodeJS

Benefits of PHP

Some developers say that PHP is much easier to use then Node.js. Their arguments are:

  • It’s easier to configure the development environment for PHP
  • Node.js requires more code
  • In order to code on Node.js, you have to understand callback functions and blockings
  • All internet hosting services support PHP
  • Supports more frameworks and CMS
  • Official code organization recommendations (PSR)
  • PHP has a larger library of instructions and frequently asked questions (there were plenty in 20 years)
  • The PHP developers community is a massive and diverse group of people, they are constantly re-visioning and updating libraries, frameworks and other PHP components

You should consider using PHP when your project includes:

  • CMS technologies such as WordPress, Drupal, Joomla, etc, even if there is only a part of your project includes these technologies (for example blog, admin page, online store etc.)
  • If you are using a relational database – go with PHP.

To sum up the whole server side of this PHP vs NodeJS comparison, PHP supports following database management systems:

  • MySQL
  • MySQLi
  • SQLite
  • PostgreSQL
  • Oracle(OCI8)
  • Oracle
  • Microsoft SQL Server
  • Sybase
  • ODBC
  • mSQL
  • IBM DB2
  • Cloudspace
  • Apache Derby
  • Informix

  • Ovrimos SQL
  • Lotus Notes
  • DB++
  • DBM
  • dBase
  • DBX
  • FrontBase
  • filePro
  • Ingres II
  • SESAM
  • Firebird/InterBase
  • Paradox File Access
  • MaxDB
  • PDO

Benefits of Node.JS

One of the main advantages of NodeJS is the support of multithreading. While it is a necessity in browsers, it is not that much needed in web development process.

“The scripting language does not need to be threaded”

Rasmus Lerdorf

A lot of developers choose Node.js over PHP. Here’s why:

  • Built-in server support
  • A single syntax for client and server side of the website. This improves the reusability of the code and makes the work of a full stack developer easier
  • Module caching – modules are downloaded and initialized when they are called for the first time, afterward they are constantly available
  • Stream module makes it easier to work with large files
  • Node has an almost identical syntax to JavaScript, thus it easy to pick-up and learn for JS developers.

Chrome V8 engine

As it was stated before, Node.js is powered by Chrome V8 engine. This engine is the source of many other benefits. You should consider using Node.JS when your project includes:

  • Streaming data transfer – traditional web stacks usually convert queries and corresponding HTTP to elementary events. However, they are data streams, and Node.js apps can take advantage of that. A great example of this kind of data stream is file processing during the download or data transfer between different layers.  
  • NodeJS supports real-time Web development – this allows to develop chats, betting apps, apps like Twitter, or interfaces for instant messaging with ease. But you have to be careful with that. Because the response time can vary, if the garbage collector interferes, he stops the execution of the program. So, don’t try to develop an app or a system with a guaranteed response time on NodeJS. Erlang is a way better choice for this job.
  • Software packages that include NodeJS, for example, MEAN (mongoDB, Express.js, Angular.js, Node.js)
  • Built-in expansion capabilities (cluster package)

Here is the PHP vs NodeJS comparison table of supported technologies:

 

PHP Node JS
CMS Magento, WordPress, Opencart, Drupal, Joomla, PrestaShop Apostrophe2, Ghost, KeystoneJS, enduro.js, Pencilblue
MVC frameworks Symfony, Laravel, Yii, Codeigniter, Zend, Phalcon, CackePHP Koa JS, Express JS, Sails JS
Realtime Ratchet, Wrench, Elephant.io, Socket.io ws, Sockjs, Socket.io
REST API RestClient, Guzzle, HTTPFUL Restify, Loopback
Scaffolding symfony+, laravel+ , yii+, CackePHP Yeoman
HTML templating Twig
Blade
Latter
Smarty
Volt
Mustache
Jade
Underscore
EJS
Handlebars
Mustache
Embedded js
Horizontal scaling implementation Elastic beanstalk, varnish Cluster mode, Amazon Elastic Beanstalk
Load balancer support + +
Queues + +
Multiple drivers support DB, storage + +
Full-text search + +
Profiling Xdebug, Blackfire, XHProf, XHGui Built in profiler
Caching Redis, Memcache Redis, Memcache
CI support Travis CI, Codeship Travis CI, Codeship
QA PHPUnit
Cucumber (behat)
Atoum
Selenium
Dusk
Kahlan
Php_testability
Codeception
Phantom.js
Jasmine
Protractor
Nightwatch.js
Casper.js
Nemo.js
Buster.js
Selenium

Benchmark

It is a good idea to choose a winner in PHP vs Node.js based on the features and benefits. However, it is always better to see how they are performing back to back, PHP vs NodeJS. We have created two different test cases and will run them on the same machine.

The test bench configuration:

  • VDS
  • CPU – 1 core, 2GHz
  • RAM – 1GB RAM
  • Storage – 10GB SSD
  • OS – Debian 8.6
  • PHP 7.0.22 FPM
  • Node.js 6.11.2

PHP vs NodeJS – First test

This test will show us how well PHP and Node.js are working with arrays,  string concatenation, network I/O, and arithmetics.

NodeJS source code:


var fs = require('fs');
var mysql = require('mysql2');

console.time('Node.js ' + process.version + ': concatenations of strings 1000000 times');
var str = '';
for (var i = 0; i < 1000000; i++) {
 str += 's';
}
console.timeEnd('Node.js ' + process.version + ': concatenations of strings 1000000 times');


console.time('Node.js ' + process.version + ': adding numbers 1000000 times');
var count = 0;
for (var i = 0; i < 1000000; i++) {
 count++;
}
console.timeEnd('Node.js ' + process.version + ': adding numbers 1000000 times');


console.time('Node.js ' + process.version + ': filling of array 1000000 times');
var array = [];
for (var i = 0; i < 1000000; i++) {
 array.push('s');
}
console.timeEnd('Node.js ' + process.version + ': filling of array 1000000 times');


console.time('Node.js ' + process.version + ': filling of associative array 1000000 times');
var array = {};
for (var i = 0; i < 1000000; i++) {
 array['s' + i] = 's';
}
console.timeEnd('Node.js ' + process.version + ': filling of associative array 1000000 times');


console.time('Node.js ' + process.version + ': reading the file 100 times');
var content;
for (var i = 0; i < 100; i++) {
    content = fs.readFileSync('./someFile.txt');
}
console.timeEnd('Node.js ' + process.version + ': reading the file 100 times');


console.time('Node.js ' + process.version + ': mysql query (SELECT NOW()) 100 times');
// create the connection to database
var connection = mysql.createConnection({host:'localhost', user: 'root', database: 'test', password: 'password'});

function promiseQuery(query) {
    return new Promise((resolve, reject) => {
            connection.query(query, function (err, results, fields) {
            resolve({err, results, fields});
        });
 });
}
for (var i = 0; i < 100; i++) {
    var a = promiseQuery('SELECT NOW()');
    a.then(({err, results, fields}) => {
        //console.log(results);
    });
}
console.timeEnd('Node.js ' + process.version + ': mysql query (SELECT NOW()) 100 times');
connection.end();

 

 

PHP source code:

<?php
$phpVersion = "v" . explode('-', PHP_VERSION)[0];

$start = microtime(1);
$str = '';
for ($i = 0; $i < 1000000; $i++) {
 $str .= 's';
}

echo "PHP $phpVersion: concatenations of strings 1000000 times: " . round((microtime(1) - $start) * 1000, 3) . "ms \n";

$start = microtime(1);
$count = 0;
for ($i = 0; $i < 1000000; $i++) {
 $count++;
}

echo "PHP $phpVersion: adding of numbers 1000000 times: " . round((microtime(1) - $start) * 1000, 3) . "ms \n";
$start = microtime(1);
$array = array();
for ($i = 0; $i < 1000000; $i++) {
 $array[] = 's';
}

echo "PHP $phpVersion: filling of array 1000000 times: " . round((microtime(1) - $start) * 1000, 3) . "ms \n";

$start = microtime(1);
$array = array();
for ($i = 0; $i < 1000000; $i++) {
 $array["s" . $i] = 's';
}

echo "PHP $phpVersion: filling of associative array 1000000 times: " . round((microtime(1) - $start) * 1000, 3) . "ms \n";

$start = microtime(1);
for ($i = 0; $i < 100; $i++) {
    $fp = fopen("./someFile.txt", "r");
    $content = fread($fp, filesize("./someFile.txt"));
    fclose($fp);
}

echo "PHP $phpVersion: reading the file 100 times: " . round((microtime(1) - $start) * 1000, 3) . "ms \n";

$start = microtime(1);
$mysql = new mysqli('localhost', 'root', 'password', 'test');
for ($i = 0; $i < 100; $i++) {
 $res = $mysql->query("SELECT NOW() as `now`");
 $now = $res->fetch_assoc()['now'];
}

echo "PHP $phpVersion: mysql query (SELECT NOW()) 100 times: " . round((microtime(1) - $start) * 1000, 3) . "ms \n";

The results:
PHP


NodeJS


As you can see PHP is faster than Node.js in:

  • Concatenation of strings
  • Filling array
  • Filling associative array
  • Reading the file
  • MySQL query

Node.js is faster than PHP only in adding numbers.

 

PHP vs NodeJS  – Second test

Now, we will test out how well Node.js and PHP are handling multi threaded tasks. We will throw at them 1000 queries in 1000 threads. Don’t look too hard into the source code, all configuration was done on the server side.

Nginx 11.7 + PHP 7.1.1 FPM vs Node.js

PHP source code:

<?php
echo "Hello world";
?>

 

 

Node.js source code:

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

 

 

 

The results:
NodeJS


PHP

The second test has ended and the results are in favor of PHP, again. The numbers are:

  • PHP + Nginx – 32 ms
  • NodeJS – 200 ms

To put this numbers into a somewhat more acceptable form, PHP is capable to process 31,250 queries per second, Node.js, on the other hand, can deal with 5,000 queries per second.

Conclusion

PHP has won in almost every category of our PHP vs NodeJS comparison. PHP is more popular and easier to learn, yet it supports a significant amount of professional programming technologies and techniques. There are plenty of sources where you can get assistance and help and the deployment process is so much easier than Node.JS.

However, don’t discount Node.JS yet. Despite its steep learning curve, it has some really serious advantages. With the help of AJAX and HTML5 you can create very efficient apps and once the code is cached, the only thing that keeps transferring is data.

In the end, there is no clear winner of PHP vs NodeJS. When you decide to create a new project, use the data presented in this article to pick what is best suited for your project and you.