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

2019-08-09 07:39发布

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条回答
倾城 Initia
2楼-- · 2019-08-09 08:21

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.

查看更多
登录 后发表回答