0

I have a loop that is used to send a json object to several HTTP client:

for(var i=0; i<clients.length; i++){
    request({
        method: 'POST',
        uri: clients[i].contact,
        json: obj
    },
    function(err, response, body){
        ....
    });     
}

Lint tells me this "W083: Don't make functions within a loop". What is the cleanest way to do this ? On top of this, I have some concern that this approach might not be that scalable (despite the usage of nodejs), what would the the appropriate approach for a high number of clients ?

Luc
  • 16,604
  • 34
  • 121
  • 183

1 Answers1

0

Benchmark: function outside loop 20 times faster on my test

// 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')

Result:

F:\damphat>node test.js
functions outside a loop =  1.032908888 seconds
functions within a loop =  20.298613718 seconds

Anyway, I think you should NOT move your callback out of the loop because it will not improve performance for your case. Just keep your code clean and readable.

damphat
  • 18,246
  • 8
  • 45
  • 59