Too many on-connection events with Socket.io, does it hurt?

不打扰是莪最后的温柔 提交于 2019-12-24 11:35:01

问题


I have an application using node.js where multiples objects has a reference to socketio implementation. Every one of them opens an on-connection event in order to add their particular events to the socket connection, like this:

this.io.on('connection', function(socket){
        socket.on('subs', function(sub){
            self.processSub(sub); 
        });
        // more events  
    });

I have like 10 of these objects and the idea is to keep adding modules using this architecture.

My question is:

Does socket.io is designed for this kind of usage ? and does it could have a serious performance consideration ?

as always, thanks for your time ;)


回答1:


eventEmitters (which a socket is) are designed for exactly that usage, so independent modules can all add their own event listeners and thus remain independent from the other listeners, but all have access to common events. This is a good and valid usage. The overhead of a listener for an event is nothing more than an array entry that holds the handler reference and then a function call to call that handler.

If you were going to have many thousands of listeners to the same event, then you might wonder a bit about the performance impact of doing so (just because of how many functions would get called), but short of that, this is what they are designed for. If your count is way less than that (you said 10), then you are perfectly fine.



来源:https://stackoverflow.com/questions/32259140/too-many-on-connection-events-with-socket-io-does-it-hurt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!