Socket.io's examples all follow this pattern
io.sockets.on("connection", function(mySocket){
mySocket.on("my message", function(myData){
...
});
});
It seems to me that this would create a new callback function for every connection. Assuming that every socket responds to the message in the same way, wouldn't it be more memory efficient to define the handler once for all sockets like this:
function myMessageHandler(data){
...
}
io.sockets.on("connection", function(mySocket){
mySocket.on("my message", myMessageHandler);
});
or even this:
io.sockets.on("my message", function(mySocket, myData){
...
});
If so, why would Socket.io recommend a practice that wastes memory? Are we expected to want to keep stateful variables for the socket inside the "connection" callback's closure?
Looking at it from another perspective, the first form is easy to read (because so many details are left out). I think this form best illustrates how the library works. Similar style is used on the Node website itself for the same reason, I believe. And I think that's precisely why it is used in those places.
After a few minutes reading blogs and discussions suggests that developers are usually opting for passing around named functions. Although I'm sure there's a performance gain in it, the primary motivation is no doubt readability. I think you'll find the second form (or a more drawn out form) to be easier to work with as your functions grow.