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:
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:
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:
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:
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:
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"
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:
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
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
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
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
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
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
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
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
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
Деcятый раунд: будущее
Это не особо важно, какой язык вы используете на стороне сервера, он все равно будет продолжать работать, даже если проект заброшен. Многие продолжают использовать PHP. Это безопасная ставка и ее поддержка выглядит уверенной еще двадцать лет.
При этом мы знаем, что восхождение Node.js было быстрым. Современный подход к развитию очевиден тем, что использует тот же синтаксис, что и на клиентской стороне. JavaScript поддерживает HTML5, веб-сокеты. Node.js неизбежно отнимает долю на рынке, но PHP, я сомневаюсь, что будет обгонять. Обе технологии имеют большое будущее. Я заявляю, этот раунд заканчивается ничьей.
Оценка судей — PHP 5:7 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
Running server side scripts using PHP as an example (LAMP)
Terms: Running server side scripts using PHP as an example (LAMP)