The most efficient way of defining Socket.io on ("message") handlers

All Socket.io examples follow this pattern.

io.sockets.on("connection", function(mySocket){ mySocket.on("my message", function(myData){ ... }); }); 

It seems to me that this will create a new callback function for each connection. Assuming each socket responds to a message in the same way, it would not be more efficient to use memory to define a 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 does Socket.io recommend a practice that takes memory? Are we expected to save state variables for the socket inside the connection callback closure?

+6
source share
1 answer

Looking at it from a different perspective, the first form is easy to read (because so many details have not been taken into account). I think this form best illustrates how the library works. In my opinion, a similar style is used on the Node website for the same reason. And I think that is why it is used in these places.

After a few minutes, reading blogs and discussions suggests that developers usually prefer to skip named functions. Although I am sure that it has performance, the main motivation is, without a doubt, readability. I think you will find a second shape (or a more elongated shape) that is easier to work with as your functions grow.

0
source

Source: https://habr.com/ru/post/921588/


All Articles