PHP VS NODE.JS: THE REAL STATISTICS一文用PHP和Node.js实现文件读写的案例展示两者性能对比, 两者相差14倍之多。究其原因还是Node.JS的异步IO。
I/O是Web应用典型的消耗瓶颈,当一个请求达到Apache web服务器时,它将动态脚本内容传递到PHP解释器 ,如果PHP脚本这时向磁盘或数据库读写数据,因为磁盘和数据库比较慢,就会造成整个请求链条的最慢一个环节。当你调用 PHP 函数 file_get_contents(), 整个线程就堵塞住了,直至等到从磁盘或数据库读写数据成功。在这段时间,服务器不能做任何事情。
如果这时还有其他用户同时发出请求,对不起,这些用户请求必须等待了,因为已经没有线程来处理这些用户请求,线程都堵塞在I/O了。
( Node.js的异步机制并不是强在Http服务器 IO内部机制上,并不如同NIO非堵塞IO那种机制,它的异步强在协调多个堵塞源)
node.js唯一卖点在这里,它能对所有IO实现异步,一旦文件获得(fs.readFile),服务器线程就空闲被其他函数调用,一旦整个I/O读写全部完成了,node会在读写完成后再调用一个回调函数 (这是之前通过fs.readFile一起传递过来的)进行后续相关扫尾工作。

下面两个脚本分别是测试脚本,功能是:
1. 接受一个请求
2. 产生一个随机数
3. 将随机数写入到磁盘文件
4. 再从磁盘文件读取
5. 返回读取内容给响应。
<?php
//index.php
$s=""; //generate a random string of 108KB and a random filename
$fname = chr(rand(0,57)+65).chr(rand(0,57)+65).chr(rand(0,57)+65).chr(rand(0,57)+65).'.txt';
for($i=0;$i<108000;$i++)
{
$n=rand(0,57)+65;
$s = $s.chr($n);
}
//write s to a file
file_put_contents($fname,$s);
$result = file_get_contents($fname);
echo $result;
<p class="indent">
|
下面是Node.js的代码:
//server.js
var http = require('http');
var server = http.createServer(handler);
function handler(request, response) {
//console.log('request received!');
response.writeHead(200, {'Content-Type': 'text/plain'});
s=""; //generate a random string of 108KB and a random filename
fname = String.fromCharCode(Math.floor(65 + (Math.random()*(122-65)) )) +
String.fromCharCode(Math.floor(65 + (Math.random()*(122-65)) )) +
String.fromCharCode(Math.floor(65 + (Math.random()*(122-65)) )) +
String.fromCharCode(Math.floor(65 + (Math.random()*(122-65)) )) + ".txt";
for(i=0;i<108000;i++)
{
n=Math.floor(65 + (Math.random()*(122-65)) );
s+=String.fromCharCode(n);
}
//write s to a file
var fs = require('fs');
fs.writeFile(fname, s, function(err, fd) {
if (err) throw err;
//console.log("The file was saved!");
//read back from the file
fs.readFile(fname, function (err, data) {
if (err) throw err;
result = data;
response.end(result);
});
}
);
}
server.listen(8124);
console.log('Server running at http://127.0.0.1:8124/');
<p class="indent">
|
测试结果:
PHP:
Concurrency Level: 200
Time taken for tests: 574.796 seconds
Complete requests: 2000
node.js:
Concurrency Level: 200
Time taken for tests: 41.887 seconds
Complete requests: 2000
<p class="indent">
|
[该贴被banq于2014-06-11 11:52修改过]
[该贴被banq于2014-06-11 19:51修改过]
[该贴被banq于2014-06-11 19:53修改过]