I'm currently working with Node.js, and have built a socket that accepts data. I am attempting to process the data in a streaming fashion, meaning that I process the data (nearly) as quickly as I receive it. There is a rather significant bottleneck in my code, however, that is preventing me from processing as quickly as I'd like.
I've distilled the problem into the code below, removing the extraneous information, but it captures my issue well enough:
require('net').createServer(function (socket) {
var foo = [];
socket.on('data', function (data) {
foo.push(data); // Accessing 'foo' causes a bottle neck
});
}).listen(8080);
Changing the code in the data
event, improves performance considerably:
var tmpFoo = foo;
tmpFoo.push(data);
// Do work on tmpFoo
The problem is, I eventually need to access the global (?) variable (to save information for the next data
event); incurring the performance penalty along with it. I'd much prefer to process the data as I receive it, but there does not appear to be any guarantee that it will be a "complete" message, so I'm required to buffer.
So my questions:
- Is there a better way to localize the variable, and limit the performance hit?
- Is there a better way to process the data in a streaming fashion?