PHP 7.1.1 FPM vs Node.js 7.4.0 в качестве web backend сервера
Всем привет, решил поделиться с вами результатами синтетического теста производительности свежих версий PHP и Node.js.
Простой VDS — 1 ядро процессора 2ГГц, 1Гб оперативы, 10Гб SSD.
ОС: Debian 8.6.
Так же произведены базовые настройки ядра, чтобы сервер в принципе мог обрабатывать большое кол-во соединений.
Тут операции, которые в основном использует backend. А именно: склеивание строк, сетевой ввод-вывод, арифметика и работа с массивами.
Код для Node.js:
var fs = require('fs'); var mysql = require('mysql2'); console.time('Node.js ' + process.version + ': склеивание строк 1000000 раз'); var str = ''; for (var i = 0; i < 1000000; i++) < str += 's'; >console.timeEnd('Node.js ' + process.version + ': склеивание строк 1000000 раз'); console.time('Node.js ' + process.version + ': сложение чисел 1000000 раз'); var count = 0; for (var i = 0; i < 1000000; i++) < count++; >console.timeEnd('Node.js ' + process.version + ': сложение чисел 1000000 раз'); console.time('Node.js ' + process.version + ': наполнение простого массива 1000000 раз'); var array = []; for (var i = 0; i < 1000000; i++) < array.push('s'); >console.timeEnd('Node.js ' + process.version + ': наполнение простого массива 1000000 раз'); console.time('Node.js ' + process.version + ': наполнение ассоциативного массива 1000000 раз'); var array = <>; for (var i = 0; i < 1000000; i++) < array['s' + i] = 's'; >console.timeEnd('Node.js ' + process.version + ': наполнение ассоциативного массива 1000000 раз'); console.time('Node.js ' + process.version + ': чтение файла 100 раз'); var content; for (var i = 0; i < 100; i++) < content = fs.readFileSync('./someFile.txt'); >console.timeEnd('Node.js ' + process.version + ': чтение файла 100 раз'); console.time('Node.js ' + process.version + ': mysql query (SELECT NOW()) 100 раз'); // create the connection to database var connection = mysql.createConnection(); function promiseQuery(query) < return new Promise((resolve, reject) =>< connection.query(query, function (err, results, fields) < resolve(); >); >); > for (var i = 0; i < 100; i++) < var a = promiseQuery('SELECT NOW()'); a.then(() => < //console.log(results); >); > console.timeEnd('Node.js ' + process.version + ': mysql query (SELECT NOW()) 100 раз'); connection.end();
echo "PHP $phpVersion: склеивание строк 1000000 раз: " . round((microtime(1) - $start) * 1000, 3) . "ms \n"; $start = microtime(1); $count = 0; for ($i = 0; $i < 1000000; $i++) < $count++; >echo "PHP $phpVersion: сложение чисел 1000000 раз: " . round((microtime(1) - $start) * 1000, 3) . "ms \n"; $start = microtime(1); $array = array(); for ($i = 0; $i < 1000000; $i++) < $array[] = 's'; >echo "PHP $phpVersion: наполнение простого массива 1000000 раз: " . 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: наполнение ассоциативного массива 1000000 раз: " . 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: чтение файла 100 раз: " . 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 раз: " . round((microtime(1) - $start) * 1000, 3) . "ms \n";
Как видно, PHP выигрывает по всем пунктам, кроме операции сложения.
Нагрузочное тестирование «Hello world». Nginx 11.7 + PHP 7.1.1 FPM vs Node.js. 1000 запросов в 1000 потоков. #ab -n 1000 -c 1000…
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://$:$/`); >);
Прогнал по 10 тестов для PHP и для Node.js и выбрал лучшие результаты у обоих.
Как видим и тут PHP выигрывает на 23% или на 628 запросов в секунду. Много это или мало судить вам.
Делитесь в комментах своими мыслями по этому поводу.
Node.js vs PHP Performance
Node.js is a powerful Javascript-based platform or framework built on Google Chrome’s V8 Engine. It is used to develop I/O-intensive web applications like video streaming sites and single-page applications. PHP stands for a hypertext pre-processer. PHP is a server-side scripting language that is embedded in a web page or can be run as a script (much Like Perl) from the command line.
Web development, programming languages, Software testing & others
Let us study much more about Node.js and PHP in detail:
Node.js vs PHP are both popular web development applications. Both node.js vs PHP can handle apps of high complexity. However, their architectures and underlying concepts are different. App owners are generally in a dilemma as to which environment to choose from. There is a range of languages to choose from, including Javascript, Python, Java, PHP.Net, C++, Go, C, Ruby, and Swift. Below is a chart showing the percentage of usage of the different languages by different users according to the user survey report of Node.js org
Head To Head Comparison Between Node.js and PHP Performance
Below are the Top 7 Differences Between Node.js vs PHP Performance
Key Differences Between Node.js vs PHP Performance
Both Node.js vs PHP Performance are popular choices in the market; let us discuss some of the major Differences Between Node.js vs PHP Performance:
- Node.js is a Javascript-based framework or platform first released in 2009, whereas PHP is a server-side scripting language that has been around for 20 years.
- Node.js is a good fit for applications that require high runtime performance, whereas PHP is more suited for blogs or e-commerce.
- LAMP stack learners (Linux, Apache, MySQL, and PHP) must master at least two PHP and SQL languages besides the mandatory HTML, CSS, and Javascript. In the case of Node.js, along with MongoDB, the entire stack can be written in one language, JavaScript.
- In the case of PHP, there are two not-very-superior package management systems, PEAR and Composer. In most cases, developers had to install it manually. On the other hand, Node.js has a superior package management system called NPM.
- PHP is easy to learn, cheap, and has excellent open-source scripts, apps, and libraries.Node.js is relatively young and suited for building real-time, NoSQL-oriented, and scalable systems.
Node.js vs PHP Performance Comparison Table
Below is the topmost comparison:
Basis Of Comparison | Node.js | PHP |
About | Authored by Ryan Dahl and initially released in 2009, Node.js is a javascript-based platform or framework for web-based applications. It is written in C, C++, and Javascript. | Designed by Rasmus Lerdorf and released in 1995, PHP, or hypertext preprocessor, is a server-side scripting language used for web development and used as a general-purpose programming language. The implementation languages include Perl, C, C++, and Java. |
Concepts | Essential concepts of Node.js are: |
- Modules
- Console
- Cluster
- Add-ons
- Buffer
- Callbacks
- Crypto
- Error Handling
- Net
- Global
- Domain
- DNS
- Streaming
- Debugger
- OOPS Concept
- Database Management
- Sessions in PHP
- Routing
- Request and Response
- Controllers
- Views
- Back-End(Including API’s)
- Full-Stack
- Front-End
- Ops/DevOps
- Desktop Apps
- Mobile
- IOT
- Security
- Custom CRM applications
- Order entry web apps
- Real Estate integration with RETS
- Automotive dealer applications
- Healthcare-related solutions
- Mobile applications development
- Website ERP integration
- Customized PHP calendars
- Encrypted PDF servers
- Asynchronous and event-driven.
- Very Fast.
- Single-threaded but highly scalable.
- No buffering.
- Licensed
- Web-Specific and open source.
- Embedded onto statin HTML files.
- Fast access to a database.
Node.js leverages JavaScript event Loop and can quickly service multiple concurrent events. This makes node.js a good fit for asynchronous, data-driven applications and heavy I/O-bound workflows, Real-time Applications, or Single-page Applications. Node.js ensures excellent runtime performance.
Using Node.js ensures one programming language across the application development stack. The same language for the front-end and back-end functions provides a maintainable application.
Node.js comes with a few rules and limitations. This contributes to creativity in developing applications.
PHP has a broad and rich code base that enables rapid application development.
PHP is very easily portable; it is designed to be run on any server like Nginx or Apache and on any platform like Windows or Linux. The code has to be written only once.
Conclusion
Regarding web performance, both Node.js and PHP Performance are very efficient. Given each app’s need, owners can choose from these two stacks the one suited to them. Below are some charts for the Node.js vs. PHP Performance market position.
Recommended Articles
This has been a guide to Node.js vs PHP Performance. Here we have discussed Node.js vs PHP Performance head-to-head comparison, key differences, infographics, and comparison table. You may also have a look at the following articles to learn more –
89+ Hours of HD Videos
13 Courses
3 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
97+ Hours of HD Videos
15 Courses
12 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
NODE JS Course Bundle — 10 Courses in 1 | 3 Mock Tests
37+ Hours of HD Videos
10 Courses
3 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5