Thursday 15 March 2012

javascript - node js event listeners. Use anonymous callbacks or declared functions for performance? -


I am writing a TCP server in Node.js which handles data coming from multiple connections. The server parses the incoming data stream and returns an object that is stored in the database. I'm trying to make some adaptations for performance, and have tested two coding behaviors:

  • Snippet 1 uses nested anonymous callback
  • Snippet 2 Declared used functions to change anonymous callback.

    I assume the slice 2 will be done faster, as it avoids the creation of the object to create new tasks for each new data packet However, in real life it seems that Slice 1 is 20% faster

    Does anyone know why

    Snippet 1:?

      Function TcpOnConnection (flow) {stream.on ("data", function (data) {parseTcp (data, function (error, obj) {if (err) console.log (err. Message); if (obj) {stream.write (Obj.returnMsg); storedata (obj);}})}}; } TCPserver.on ("Connection", TCPO Connection);   

    snippet 2:

      function TcpOnConnection (stream) {function handleParsed (hey, obj) {if (mistake) console.log (err.message) ; If (obj) {stream.write (obj.returnMsg); StoreData (obj); }} Function stream data (data) {parseTcp (data, hand persaded); } Stream.on ("Data", StreamOnadata); } TCPserver.on ("Connection", TCPO Connection);    

    A function declaration does not refrain from creating a new function object or just closing One function is declaration - in this respect they have the same mechanics. And in fact you are not just creating a function object but there is also a regular object (each function comes with a fresh object that you can refer to with .prototype , though at least V In 8 it seems that it only made when necessary).

    Functions are first-class objects, which have a negative effect on creating a separate object for each function.

    Ensure that all your functions are either within a module scope or a function that only executes once per application:

      function handles percussion (err, obj) {If () error console.log (err.message); If (obj) {// what I am doing here is possible only if // `it` refers to the stream / / it depends on how parseTcp calls callback. Write (obj.returnMsg); StoreData (obj); }} Function stream data (data) {parseTcp (data, hand persaded); } Function TcpOnConnection (stream) {stream.on ("data", stream-ondata); } TCPserver.on ("Connection", TCPO Connection);    

No comments:

Post a Comment