PHP vs Nodejs

Lecture



It is always better to explain something by a clear example with pictures. Therefore, let's invent a small “spherical site in a vacuum” and accept some conditions.

Suppose we have a site that understands only two requests:
Request A is executed in 1 second, it does not require access to the database.
Request B is executed in 5 seconds, and 4 of them, it spends waiting for the response of the database.
We also agree that the time between requests is at least 1 second.

Php


Let's take a look at how this works on php.
In its most simplified form, the server architecture looks like this:

PHP vs Nodejs

The following is important here, the web server receiving a request from the client sends it to the php process. In turn, the php process can process one request at a time, upon completion of the work, the result is returned to the web server, and the process itself ceases to exist. The web server receiving the response sends the result to the client and closes the connection.

If there is only one php process, the work of our server can be displayed on this scheme:

PHP vs Nodejs

It is clear from the diagram that as long as only requests come to us, our server responds to them vigorously and generally performs its tasks, but as soon as request B comes to us, the server stops responding to requests until the answer to request B is ready. Also on the diagram you can see that most of the time query B, “everyone” waits for the result of the database operation.

To solve this problem, we have to increase the number of php processes, let's increase to 2x, as a result, the scheme takes the following form:

PHP vs Nodejs

From this scheme, it is clear that request B “hangs” in processing in the first php process, while the server continues to respond to other requests. Everything will go well until the moment when two requests B come to us, then both php processes will “hang” waiting for the base to respond, and the server as a whole will stop responding until one of them is free.

Well, we already know what to do? That's right, let's take and increase the number of php processes, immediately to 20 or 30 and the problem seems to be gone, although in fact the problem just drifted away a bit and the moment when 30 requests came B comes. The whole trouble is that we can not create infinitely many php processes and the way to increase them in exorbitant quantities is incorrect.

The most important thing that should be taken out of these schemes is that the operations of working with the database in php are performed synchronously. In our case, the process that performed the query to the database is unable to process other requests and is forced to “hang” (without doing anything) expecting a response from the database.

nodejs


What does nodejs give us?
First, let's see how a simple server looks like:

PHP vs Nodejs

Immediately striking is the fact that the server includes the processors of requests A and B directly, as well as the Web server itself. All this stuff turns in one node process and constantly hangs in memory.

Let's look at the scheme of work:

PHP vs Nodejs

The diagram clearly shows that requests B do not cause the server to “hang” while waiting for the base to respond. The server receiving the request B, simply generates and sends the request to the database, and will continue to respond to other requests, as soon as the response from the database is received, the server will return the result to the client. In the case of nodejs, it doesn’t matter how or how many B requests come in, none of them will lead to “hanging” waiting for the base to respond.

Conclusion


And the conclusion is simple.
Having come to nodejs do not try to do something the way you did in php.
Remember that you are working in an asynchronous environment, do not use blocking operations, you are killing the idea of ​​nodejs.
Remember that nodejs handles many requests in one process that are constantly hanging in memory, so watch your variables and how you use memory.
You should not run 50 node processes for one site, and generally you should not run them more than the number of cores on the processor, more of them only slow down the work as a whole.
A nodejs is not a silver bullet and its use alone will not solve the problems of scaling and work under heavy loads.

There are many articles on this topic, with qualitative characteristic analyzes and performance predictions. However, I still wanted to find an article where professional programmers share their opinions and try to tell something, to warn a beginner who is just learning PHP or NodeJS (server-side JavaScript). Many people do not like PHP and say that PHP was created to die (yes, there is a garbage collector that kills our variables after the script is executed, and not because Rasmus Lerdorf abandoned it), however, that now you don’t learn PHP at all, while while it works 80% of sites on the Internet. Therefore, if we want to be professionals and try to somehow expand our horizons, we need to clearly separate the PHP tasks and the NodeJS tasks, and not merge everything into a heap.

"10 rounds of boxers of different weight categories"

PHP vs Nodejs

One fine day, Craig Buckler published a comparative analysis of PHP and NodeJS called “10 rounds” on SitePoint.com to determine who is the absolute champion. However, at the same time, he noted that such an analysis is somewhat controversial. Therefore, for some entertainment, he invited two judges who would contribute to this boxing match. He asked Bruno Shkvortsa (Bruno Škvorc, PHP column editor on SitePoint.com) and James Hibbard (James Hibbard, JavaScript column editor on SitePoint.com) to comment on each of the rounds, blow by blow - score.

Introduction


Web programming is rapidly evolving, and back-end developers face the question of choosing between established Java, C, Perl heavyweights and modern web-based languages ​​such as Ruby, Clojure, Go. Your choice is of great importance, imposing its imprint on the application.

But what choice to make for web development?

I don’t want to start a holivar, but today we’ll talk about PHP and NodeJS:

  • PHP - was created in 1994 by Rasmus Lerdford (Rasmus Lerdorf). He created a software shell (interpreter), which is installed as a module for the Apache or Nginx web server. Initially developed as a preprocessor of hypertext pages, so PHP can be easily integrated into HTML code, however, this approach is not a good practice now, but still for beginners, this approach was obvious. This contributed to the popularity of the language, so 80% of the websites on the Internet are written in PHP, and they, in particular, are running WordPress CMS (20% of the websites on the Internet).
  • Node.js - was created in 2009 by Ryan Dahl. He created a software platform based on JavaScript engine V8 from Google. Unusually, the platform has built-in libraries for processing requests and responses, thus you do not need to use a third-party web server and any other dependencies. Node.js is gaining momentum and is used by companies such as Microsoft, Yahoo, LinkedIn and PayPal.

Why not talk about C #, Java, Ruby, Python, Perl, Erlang, C ++, Go, Dart, Scala, Haskell, and others?


Would you read an article about everything and everyone, do you need an encyclopedia? Therefore, we restricted and narrowed the circle to two famous ones because:

1. PHP and Node.js are web-based, both are open source, they are directed exclusively to web development.
2. PHP is an old language, however, Node.js in our case is an upstart, which is gaining momentum in popularity, so a php developer should wonder. Is it worth changing technology?
3. Many developers program from far 90s to PHP and JavaScript, and not everyone wants to switch to other programming languages, because they don’t give them their due.

rules


The boxer in the right corner is PHP, the boxer in the left is Node.js. The absolute winner will be the technology that wins by the number of rounds.

Round One: Quick Start


In this round, we determine how quickly we can write the “Hello, world” page in a particular programming language, at which time we include the time spent setting up the server.

Prepare the environment:



1) How fast can you build a “Hello World” web page in PHP:

 


This code can be written anywhere, as a rule, the code is written in files ending in the .php extension. If you wrote this code in the index.php file and launched it on the local server through port 8000 (on your computer, and not on a real hosting), then its display will be available at:

 http://localhost:8000 

.
However, using a ready-made PHP interpreter with a built-in server is rather unreliable. It is better to use ready-made solutions, Apache builds - XAMPP or virtual OS (Vagrant). By the way, you can upload your file to any internet hosting.

2) Installing the Node.js platform is easy if you work on unix-like systems, you can do it with the help of package managers. Let's create an index.js page:

 const http = require('http'); const hostname = 'localhost'; const port = 8000; http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Hello World\n'); }).listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); }); 


We repeated similar actions, JavaScript code, as a rule, is written in files ending in the .js extension. If you wrote this code in the index.js file and launched it on the local server through port 8000 (on your computer, and not on a real hosting), then its display will also be available at the address (provided that php is now running on another port) :

 http://localhost:8000 


Now let's evaluate the code, even if you know client-side JavaScript well, you will have to think and understand what is written here. You have to understand closures and callback functions, promises, programming on the Node.js side requires some skill.

PHP is conceptually simpler and wins this round. Although PHP has several software dependencies, PHP is less difficult to learn.

Judges Score - PHP 1: 0 Node.js

  • Bruno: PHP wins due to low entry threshold. There is more a question of perception. On the screen they are displayed equally and they have no significant difference. In fact, the syntax is much easier for newbies to programming.
  • James: When developing on a local machine, I don’t see the difference between them. To run the script in a browser, you need to have a web server and a terminal. In order to do something serious on Node.js, you need to install additional modules, for example, express (a framework for web applications). However, conceptually PHP is simpler.

Second round: help and support


In fact, you will not go anywhere on your knowledge without studying any courses, modern practices, in order to develop, you need to ask questions on forums such as StackOverflow. PHP wins this round easily, it has a great guide on php.net and twenty years of frequently asked questions. Whatever you do, someone faced this problem and tried to solve it for you.

Node.js has good documentation, but the technology is quite young, so the answers on the forums will be much less.

Judge Rating - PHP 2: 0 Node.js

  • Bruno: said nothing
  • James: I agree. Node.js is a younger technology, so now it’s worse with support and documentation. This problem, however, becomes less and less serious as the Node matures.

Third Round: Language Syntax


Unlike some languages ​​and frameworks, PHP will not force you to work in a certain way, and it grows with you. You can write your small programs on simple PHP4 functions, and they will be different in their beauty from MVC PHP 5+. However, in this case, your code can be chaotic, you will start writing the best code only with an understanding of some things.

PHP syntax changed with the release of new versions, because of which the work was carried out on backward compatibility. You can easily migrate code from PHP4 to PHP5. However, as a consequence of this approach, a mess (porridge) has formed in PHP.

For example, how do you calculate the number of characters in a string?

- count ()? str_len ()? strlen ()? mb_strlen ()?

You will find several functions in the documentation for this, but in fact, everything is simple. In general, there are many functions in PHP that work in the same way, try writing a few lines of code without consulting with a mentor.

  


C Javascript is different:

  var len = ('Hello world').length; console.log(len); 


We see that JavaScript is relatively clear at the same time, with several major trends. Its object-prototype model attracts developers, and the syntax seems to be pretty light, but it’s not. You will find criticism about mathematical errors (0.1 + 0.2! = 0.3) and dynamic typing ('4' + 2 == '42' and '4' - 2 == 2). But these situations rarely cause problems, and all languages ​​have features.

PHP has many advantages, but Node.js wins for some reason:

1. JavaScript seems to be the most incomprehensible language in the world, but as soon as you grasp its concept, other languages ​​become cumbersome compared to it.
2. JavaScript looks smaller than PHP, you do not need to deal with the same UTF-8.
3. Full-stack developers can write JavaScript code on both the client side and the server side. You no longer need to switch between technologies.
4. Studying JavaScript, you would like to write more and more in this language, this cannot be said about PHP.

Judge Rating - PHP 2: 1 Node.js

  • Bruno: I strongly disagree with this point. Although PHP has its own characteristics, many of them have been fixed recently, and many oddities are removed in the newest versions. On the other hand, exactly the same is in the JS world. With regards to the server part, then I also do not agree. The client side and the server side are different things, and you, in any case, will have to switch your brain, the same syntax on the server if we write to Node.js if we write JavaScript code for the browser. Having worked with JS and PHP, in due time, I like the first less and less, although these are purely personal preferences.
  • James: I love javascript. I know, it has its quirks, and I know that there are several pitfalls, but ECMAScript 2015 fixes a lot while adding interesting new features to the language. JavaScript is both powerful and flexible, and can accommodate many different programming styles. Unlike PHP, I love writing in JavaScript. Node.js wins this round.

Fourth Round: Developer Tools


Both technologies have a good selection of editors, IDEs, debuggers, validators, and other tools. Here you can draw a draw, but still Node.js has a great tool, npm is a package manager, with its help you can manage modules and dependencies.

PHP has its own package manager, developed under the influence of npm - Composer. However, if npm is built in by default, the composer will have to be built in by itself. Thanks to npm, Gulp has become widespread, Grunt - build systems for front-end projects.

Judges Score - PHP 2: 2 Node.js

  • Bruno: While the composer was originally inspired by npm, now it's even better than npm. Composer will not damage your system if you want to install two versions of the same library, unlike npm. Also, unlike npm, composer can set recursive dependencies, while npm just can't do it. Npm also has completely terrible error messages, which are called “friendly”. Finally, npm doesn't really work with Vagrant, and thus prevents you from getting started properly, not to mention the fact that they do not pay attention to the desires of their users. There was an error that was open for many years, because of which it was not suitable for users on Windows - this is hardly a small user base. PHP has its own share of errors, of course, also stupid, but they have not repelled whole operating systems for many years.
  • James: I love npm. It's easy to use, and there are thousands of packages available for almost any need. I also like the fact that npm allows you to choose between global and local installation of packages (as opposed to languages ​​like Ruby, where this is the standard for your gems). Tools such as bower and grunt have a permanent place in my work, and have increased my productivity many times over.

Fifth Round: Wednesday


Where can these technologies be used? How to deploy them? What platforms are supported? Web developers often need to create applications that are only related to the web, for example, developing an online service, data conversion scripts, etc.

In PHP, you can develop desktop applications or console utilities, but mostly PHP is needed on the server side and rarely goes beyond that.

A few years ago, JavaScript was used exclusively for the browser. With the advent of Node.js, you can write desktop and mobile applications, and you can also program microcontrollers. Node.js has extended the boundaries of JavaScript.

Judges Score - PHP 2: 3 Node.js

  • Bruno: Well, first, we compare PHP with Node.js, and not PHP with JS. Secondly, we compare languages ​​and environments where they can work. To say that a monkey is better than a fish, because the fish could not climb a tree is just silly. But both monkeys and fish can swim, so let's compare how well they do it.
  • James: Several features that make Node.js so popular (speed, scalability, compatibility with JSON, low resource utilization) allow it to be used for many other uses, for example, powering microcontrollers (IoT). I mean, who doesn't love robots?

Sixth Round: Integration


Your development technologies will be limited, unless they can integrate with databases and drivers. PHP is strong in this area. The development has been for many years, and its system extensions allow direct work with any host using the API.

Node.js is catching up quickly, but you can pretty much sweat to find modern integration components for old stuff.

Judges Score - PHP 3: 4 Node.js

  • Bruno: I'll draw here. PHP has an age advantage, giving it more options, but even here it was possible to suffer from some obsolete integrated things, for example, the MySQL extension, which we finally managed to get rid of in PHP7.
  • James: Not sure I agree with that. I would hope by the example of “old, less popular things in technology”. One of the main advantages of Node.js is that it understands JSON. JSON is probably the most important format for exchanging data on the Internet, or interacting with NoSQL databases. When you work with Node.js, data can flow neatly in layers without the need for reformatting. You have one syntax when communicating with the database.

Round 7: Hosting and Deployment


How easy is it to deploy new applications on a real web server? There is another clear PHP victory. Any internet hosting supports PHP. You can get MySQL database at a bargain price. PHP is much simpler than a sandbox (local server) and you will be notified exactly which PHP extensions are disabled and which ones are not.

Node.js is a completely different beast, and it can work on the server side all the time, without breaking the connection. For this, you will have to look for specialized hosting. You need a virtual cloud (VDS / VPS, server environment, with full access). Unfortunately, not all hosters can afford this, so prices will be appropriate.

Judges Score - PHP 4: 4 Node.js

  • Bruno: silent
  • James: In the future, Node.js will catch up. Typically, the PHP web server is distributed with MySQL. To see some kind of php code, all you need to do is create a file with the .php extension and shove the code between , Upload the file to the server, enter the path to this file in the address bar. The same cannot be said about Node.js. There are, of course, many hosting options for Node.js, but they invariably require more detailed configuration and access to the command line, which potentially repels beginners.

Eighth Round: Performance


PHP does not slouch and there are real projects, and options that allow PHP to work faster. Even the most demanding PHP developer rarely cares about speed, but Node.js performance is usually better. Of course, performance is largely a result of experience and team development, however, Node.js has several advantages:

1. Less dependencies
All requests to the PHP application should be directed to the web server, which runs the PHP interpreter, which processes the code and sends it. Node.js does not need so many dependencies, and although you are almost certainly using a framework on the server, such as express, it is quite lightweight and manages part of your application.

2. Fast interpreter
Node.js is smaller and faster than PHP. This is due to the legacy of Google, which made a huge contribution to the performance of the JavaScript engine - V8.

3. Applications work constantly
PHP performs the usual client-server model. Each page request initiates an application, loading database connection parameters, extracting information, and displaying HTML code. In Node.js, the application is constantly running and needs to be initialized only once. For example, you can create a single database connection object, which is reused for a new query. True, there are ways to implement this behavior in PHP using special systems such as memcached, but this is not a standard function of the language.

4. Event, non-blocking I / O stream
PHP and most other server languages ​​use an obvious blocking model. When you make a request to retrieve information from the database, the request will complete and complete the process before moving on to the next operator. Node.js is different. Node.js need not wait. Instead, you can create a callback function that, while listening to the process, is executed after the action is completed.

Though Node.js applications are noticeably faster than PHP has its own pitfalls here.

Node.js / javascript runs in one thread, and most web servers are multi-threaded and process requests in parallel. Writing asynchronous code is difficult and carries its own problems.

Judges Score - PHP 4: 5 Node.js

  • Bruno: Misconceptions abound. First, performance discussions are controversial. Any performance gains depend solely on the experience of the developers and the type of application. But even if this message is not convincing, here are some of my own arguments: PHP works quite well with a multi-threaded embedded web server, this allows you not to use the external server completely, but this is not recommended (for now). There are also super fast servers, such as Nginx, which make the whole process of running PHP and delegating requests to it imperceptible. Projects such as HHVM and Appserver add powerful asynchronous and multi-threaded aspects, PHP7 itself will be much more powerful with the updated version. Yes, the php application receives only static, and lives only once per request, however, this can be circumvented: memcached, ajax. JS server applications run in one request by default. PHP needs to constantly make requests to the page in order to update it, but more than that - the life of a single request is only an advantage, because we make a request again for PHP, our application is restored (every time you request) when it is used, thus we we avoid problems with memory, cleaning of garbage.
  • James: Node.js is distributed as a platform with high performance, low application latency. Thanks to non-blocking I / O mechanism and Google Chrome V8 technology, Node.js has become synonymous with the words “fast” and “scalable”. There are numerous stories about how Node.js brought significant productivity gains to the company and produced an increase in developer productivity. I am pleased with this, but again, this is a controversial point.

Round nine: programming passion


It's a bit hard to compare, but relatively few PHP developers are passionate about the language itself. When was the last time you read an PHP article or watched a presentation that captivated the public? Perhaps all that was said? Maybe there is less fun? Maybe you do not look in the right places? There are some interesting features that have appeared quite recently, for example, the appearance - PHP7, but still this technology has been trampling for several years. This affected the language itself, many developers began to scold PHP.

JavaScript shares a community. There are those who love him and those who hate him, few developers sit on the fence. However, the responses on Node.js were largely positive and the technology is on the crest of a wave. This is partly because it is new, at the moment, Node.js wins this round.

Judges Score - PHP 4: 6 Node.js

  • Bruno: You certainly look in the wrong places. The PHP community is incredibly passionate and very active. There are more than 20 major conferences a year, and some amazing topics get their discussions. The emergence of HHVM and PHP7 also makes itself felt. In addition, I would like to say that it is interesting when you see that the Node.js developers still did not learn how to change the version numbers (version v0.12.5 at the time of this writing), even after 6 years of development. Many immaturities, combined with critical but ignored old bugs, can repel entire operating systems, all of which is something a serious developer will think twice. I do not like Node.js. Moz hostility is based on negative experiences mainly when working with npm. It is possible that everything will change in the future, but now, I am full of fear and despair when I have to use Node.js again. У всех нас есть свои предпочтения, но важно, чтобы все это оставалось объективным, нам нужно выбирать правильный инструмент для своей работы. Также важно признать, что иногда выбор правильного инструмента влечет за собой неправильный выбор другого. Не слушайте никого. Попробуйте сами — посмотрите, что работает, выясните, что вы чувствуете. В конечном счете, именно то, что вы делаете заставляет вас чувствовать себя продуктивным и это является лучшим выбором, а не тот выбор, который дает вам миллисекунды дополнительного прироста.
  • Джеймс: В сообществе Node.js очень жарко. Существует много открытий в Node.js-мире. Несмотря на то, моя страсть является субъективной, я рад, что Node.js выиграл этот раунд.

Деcятый раунд: будущее


Это не особо важно, какой язык вы используете на стороне сервера, он все равно будет продолжать работать, даже если проект заброшен. Многие продолжают использовать PHP. Это безопасная ставка и ее поддержка выглядит уверенной еще двадцать лет.
При этом мы знаем, что восхождение Node.js было быстрым. Современный подход к развитию очевиден тем, что использует тот же синтаксис, что и на клиентской стороне. JavaScript поддерживает HTML5, веб-сокеты. Node.js неизбежно отнимает долю на рынке, но PHP, я сомневаюсь, что будет обгонять. Обе технологии имеют большое будущее. Я заявляю, этот раунд заканчивается ничьей.

Оценка судей — PHP 5:7 Node.js

  • Бруно: молчание .
  • Джеймс: Ничья была справедливым результатом этого раунда. Node.js является восходящей звездой, но массивный PHP ему не свергнуть. В завершение можно добавить, если ваш инструмент кажется молотком, то каждая проблема кажется гвоздем. Node.js не идеально подходит для каждого сценария, и в самом деле лучше много раз подумать, когда и где, имеет смысл использовать его. Тем не менее, там где Node.js плох, это даже очень хорошо. Вы сможете сделать осознанный выбор и выбрать лучший инструмент для своей работы.

Абсолютный победитель


Final score 5: 7 in favor of Node.js. Node.js has a steep learning curve and is not ideal for novice developers, but it still wins. Simply. If you are a competent JavaScript programmer who loves his language, Node.js will not disappoint you. You will feel refreshed and gain a liberating web development experience. But do not dump PHP. PHP is alive, and there is little reason to run PHP, because it looks fashionable. PHP is easier to learn, you can learn professional programming techniques, the main practice. PHP is very easy to deploy on the server. Even obstinate Node.js developers should use PHP for simple sites and applications.

My advice: evaluate the options and choose a language based on your requirements. It is much more practical than relying on the pros and cons!


Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Running server side scripts using PHP as an example (LAMP)

Terms: Running server side scripts using PHP as an example (LAMP)