高性能nodejs静态文件模块ifile前瞻

前不久刚写了一个iroute的nodejs路由模块,可以用于http/https的框架或者应用中,当然也可以轻松整合到express框架里,将比express自带的原生路由在10000并发,1000个路由的压力下响应速度提升4-5倍。

最近由于工作较忙,另外一个模块的开发一直比较缓慢,ifile模块。这个模块主要是用于让nodejs更加简单高效的实现一个轻量级的静态文件http/https服务器,遵循http协议,采用libuv的多线程异步模型,同时也能很方便的嵌入express框架,相信随着ifile和iroute的加入,将对express的路由性能和静态文件性能提升不少。

ifile模块目前已经将路由功能,匹配规则功能,以及输出文件功能开发完毕,下阶段需要加入一些静态文件的minetype,计算last-modify,etag,gzip等。现将简单的测试报告记录一下:

测试用例,nodejs版本
var fs = require(‘fs’);
var times = 1000;
var count = times;
console.time(‘node’);
for(var i=0;i<times;i++){
fs.stat(dirname+’/static/jquery.1.7.1.js’, function(err,stats){
if(err) throw(err)
var size = stats.size;
fs.readFile(
dirname+’/static/jquery.1.7.1.js’,function(err,buf){
if(err) throw(err)
var jquery = buf.toString();
if(!–count){
console.timeEnd(‘node’);
}
})

})
}

nodejs测试用例说明,循环执行1000次,先获取文件的大小,然后将文件tostring()保存在变量中,其中没有任何的路由匹配,规则匹配。
在i5,WIN8笔记本执行结果如下:
F:\github\ifile\benchmark>node benchmark_node.js
node: 172ms

F:\github\ifile\benchmark>node benchmark_node.js
node: 170ms

F:\github\ifile\benchmark>node benchmark_node.js
node: 171ms

F:\github\ifile\benchmark>node benchmark_node.js
node: 174ms
接下来我们使用ifile模块,执行相同的事情,循环1000次。
var times = 1000
var count = times;

var ifile = require("../index.js");

ifile.add([
    ["/static/",__dirname],
],function(req,res){
    throw(404)
    //console.log('404')
})

var req= {
    url:'/static/jquery.1.7.1.js',
    method:'GET'
}

var res = {
    end:function(buf){
        var jquery = buf.toString();
        //console.log(jquery)
        if(!--count){
            console.timeEnd('ifile');
        }
    }
}
console.time('ifile');
for(var i=0;i<times;i++){
    ifile.route(req,res);
}

ifile模块同iroute模块api接口一摸一样,只有2个,一个ifile.add增加规则,一个ifile.route来匹配和相应,执行结果如下:
F:\github\ifile\benchmark>node benchmark_ifile.js
ifile: 149ms

F:\github\ifile\benchmark>node benchmark_ifile.js
ifile: 150ms

F:\github\ifile\benchmark>node benchmark_ifile.js
ifile: 152ms

F:\github\ifile\benchmark>node benchmark_ifile.js
ifile: 153ms

F:\github\ifile\benchmark>node benchmark_ifile.js
ifile: 151ms

可见ifile模块在匹配路由和执行js回调函数的情况下甚至比原生未加任何判断的nodejs代码还要快10%以上,相信在完成ifile模块之后,确实可以让nodejs和nginx的静态文件响应速度拉小差距了。

最后附上一张ifile和普通nodejs的静态文件处理流程图