Most efficient way to define Socket.io on("message") handlers

Viewed 1807

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?

2 Answers

Defining Socket.io in most efficient way:

   io.on('connection', function (socket) {
   socket.on('new-message', function (data) {
       io.emit('emit-message', data)
        });
   });

Or

   io.on('connection', (socket) => {
   console.log('user connected');

   socket.on('disconnect', () => {
       console.log('user disconnected');
        });
   });
Related