简体   繁体   中英

JavaScript Variable Access Performance

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?

dont use anonyme functions like that:

 createServer(function (socket) {

Define functions seperately and call these as follow:

 var foo = [];

 function createMyServer(socket) {    
      socket.on('data', reveiveDataFromSocket);
 }

 function reveiveDataFromSocket(data) {
      foo.push(data);
 }

 require('net').createServer(createMyServer).listen(8080);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM