>我有一个循环,用于将 json 对象发送到多个 HTTP 客户端:
for(var i=0; i<clients.length; i++){
request({
method: 'POST',
uri: clients[i].contact,
json: obj
},
function(err, response, body){
....
});
}
Lint 告诉我这个"W083:不要在循环中制作函数"。最干净的方法是什么?最重要的是,我担心这种方法可能不那么可扩展(尽管使用了nodejs),对于大量客户端来说,合适的方法是什么?
基准测试:在我的测试中,循环外的功能速度提高了 20 倍
// FILE: test.js
// note: 1e9 == 10^9
var begin, end;
// TEST sum function outside
begin = process.hrtime();
function sum(a, b) {
return a + b
}
for(var i=0; i< 1e9; i++) {
sum(i, i);
}
end = process.hrtime(begin);
console.log('functions outside a loop = ', end[0] + end[1] / 1e9, 'seconds')
// TEST sum function within a loop
begin = process.hrtime();
for(var i=0; i< 1e9; i++) {
(function sum(a, b) {
return a + b
})(i, i);
}
end = process.hrtime(begin);
console.log('functions within a loop = ', end[0] + end[1] / 1e9, 'seconds')
结果:
F:damphat>node test.js
functions outside a loop = 1.032908888 seconds
functions within a loop = 20.298613718 seconds
无论如何,我认为您不应该将回调移出循环,因为它不会提高您的案例的性能。 只需保持代码干净且可读即可。