Free estimation Response in 24h

PHP vs NodeJS Comparison and Benchmark

39 sharings

Article Content

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

php vs nodejs first test php
NodeJS

php vs nodejs first test 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 vs nodejs second test nodejs
PHP

php vs nodejs second test 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.

39 sharings

Follow our newsletter

No spam! Only best research and reviews in Web Development

4 comments

Avatar
Matthew Kernes
21:50
09.10.2017

The comparisons are pretty much garbage. Neither of these tests are real-world applicable tests. Constructing a single “Hello World” test, for example, is not exactly performing an apples-to-apples test.

If you wanted to perform the same test, you could just as easily configure nginx to spit out the result of “node test.js” with “console.log(‘hello world’);” as the only line of text in the code. In this case, it’s still possible that PHP will out-perform Node. Though, the test would actually be closer to accurate.

Put this into a real world scenario where you’re actually measuring performance of concurrent connections on sites with dynamic data and more than one page/module; that’s where things change. Node manages multiple concurrent connections better because it is not opening a new Node executable instance each time a request comes in, resulting in fewer PIDs and far less memory usage. PHP opens a new parsing instance with each request. If, in the real world, your webpage was actually “Hello world”, then PHP would be the right tool for the job.

But nobody’s website is actually “Hello world”. Websites are often intricate. And web apps are far more intricate. Managing hundreds (if not thousands) of concurrent connections requires a LOT more hardware with PHP than with Node because you run into limitations of memory. Even opening a PHP instance for “Hello World” for two connections is already double what you open for one. Rinse and repeat for hundreds of connections and you start to see a memory profile that looks like a tall hill.

On the other hand, do the same for Node, and the memory profile will remain mostly flat. Only a single instance must be open to manage multiple connections. (Though, many cluster node on machines with multiple CPU cores to exponentially increase connection handling.)

This is where real-world statistics comes into play:
If you have a website with low concurrent connections, PHP is an excellent solution because it’s quick to develop on. But if your site has lots of users constantly connected or making connections, Node.js is a far better solution, though may take a bit more scaffolding to get started.

I’m both a PHP and Node.js developer. I’ve much experience in both languages. I’ve been working in PHP since PHP 4, and I’ve been working with Node.js since 0.9. In both cases I’ve used them for their strengths in the right places. I can tell you with 100% certainty that this blog post is extremely biased (towards PHP) and doesn’t properly explain the strengths of Node.js. You might as well say, “Look how much better PHP is for websites than .” It also further misleads the reader that PHP can do things Node.js can’t. (i.e. “Here’s what DBs work with PHP”, no list for Node.js)

Furthermore, the conclusions of these tests don’t add up correctly. Supposedly, you’re transferring “Hello World” 50,000 times in each test. Yet, both tests have a different amount of transferred data in the tests. In one hand, you can say that PHP transferred more data faster. On the other hand, I can say PHP just cost me a lot more money to do the same thing I could have done in Node. So you have to explain the massive discrepancy in HTML transferred, at a minimum.

A proper test would include tests where Node.js would accel at as well, but it’s conveniently missing in this blog. Here’s a hint: Do a high concurrency test with PHP reading and writing to SQL and returning data. Then do the same with Node.js. Also, don’t use a 3rd party library like “mysql2” to connect to MySQL in Node.js. It’s significantly slower than the actual “mysql” library. (You could have found this out if you wanted to.)

BTW, I tested your script on my local, and first thing I noticed was that my numbers were totally different than yours. Obviously the (ms) would be different because we have different hardware/OS setups, but the numbers were sometimes flipped totally. For example, the “adding numbers 1000000 times” in your test takes about as much time as filling an array. On my rig, it takes 1/5th the amount of time as filling an array. There’s clearly a big discrepancy in either your rig’s hardware or your node environment optimization (which is why these results are far from scientific).

Finally, I recommend doing some research on what scientific tests look like. Performance benchmarking on your local computer as you’ve done is far from scientific and has no control cases. You provide very little information about the strengths of each server-side implementation, as well as providing no information about the system you tested on, let alone the OS and what type of installation and optimization for each server type you use for testing.

I recommend staying away from these types of hatch-job tests if you want to make have a credible name in the industry.

    Avatar
    Yana Gusti
    11:28
    14.10.2017

    Hi Matthew,

    It is all relative, if you want to improve such comparison, you are welcome and we are ready to add your impact.

    Comapre PHP and Node.JS is same as comparing chocolate and orange. In any way, we are getting a lot of questions regarding backend, so decided to create such article.

    Alex

Avatar
dev py
09:08
27.09.2017

Results and conclusions in this article are questionable.

Avatar
Adam Wysocki
22:30
25.09.2017

so making OnceBuilder CMS based on PHP was good idea