I'm writing a TCP server in Node.js that handles incoming data from multiple connections. The server parses the incoming data stream and returns an object which is stored in a database. I'm trying to do some optimization for performance, and tested two coding practices:
I assumed snippet 2 would be faster, as it avoids the creation of new function object for each new incoming data packet. However, in real-life it seems that snippet 1 is 20% faster.
Does anyone know why?
Snippet 1:
function TcpOnConnection (stream) {
stream.on("data", function(data) {
parseTcp(data,function(err,obj) {
if (err) console.log(err.message);
if (obj) {
stream.write(obj.returnMsg);
storeData(obj);
}
});
});
}
TCPserver.on("connection",TcpOnConnection);
Snippet 2:
function TcpOnConnection (stream) {
function handleParsed(err,obj) {
if (err) console.log(err.message);
if (obj) {
stream.write(obj.returnMsg);
storeData(obj);
}
}
function StreamOnData(data) {
parseTcp(data,handleParsed);
}
stream.on("data", StreamOnData);
}
TCPserver.on("connection",TcpOnConnection);
A function declaration doesn't avoid creating a new function object or a closure just because it's a function declaration - they have same mechanics in this regard. And in fact you are not just creating a function object but a regular object too (each function comes with a fresh object that you can reference with .prototype, although at least in V8 it seems that it is only created when needed).
Functions are first-class objects, that has a downside of having to create a separate object for each function no matter what.
Make sure that all your functions are either created either in module scope or inside a function that only executes once per application:
function handleParsed( err, obj ) {
if (err) console.log(err.message);
if (obj) {
//What I'm doing here is only possible if
//`this` refers to the stream
//That depends how parseTcp calls the callback
this.write(obj.returnMsg);
storeData(obj);
}
}
function StreamOnData( data ) {
parseTcp( data, handleParsed );
}
function TcpOnConnection (stream) {
stream.on("data", StreamOnData);
}
TCPserver.on("connection",TcpOnConnection);