'Socket.io disconnect events and garbage collection for related closure

I have a basic real-time server that uses socket.io. My question involves closures and garbage collection as well as whether I should bother storing socket connections in an associative array or just leave it to the closure to manage the connections.

One question I have is if a socket connection disconnects, will the same socket connection attempt to send a message if emit is invoked on the disconnected socket? In other words, what happens when you call socket.emit() on a disconnected socket?

Here's some code, questions at the bottom:

 var socketio = require('socket.io');
 var io = socketio.listen(server);
 var EE = require('events').EventEmitter;
 var ee = new EE(); //this is actually initialized elsewhere but now you know what it is

 var connectedUsers = {}; //associative array to store socket connections by socket.id

        io.on('connection', function (socket) {

           connectedUsers[socket.id] = socket;  //should I bother storing the socket connections in the associative array or just leave it to the closure to store them

            socket.on('disconnect', function () {
                connectedUsers[socket.id] = null; //should I bother removing
            });

            ee.on('update',function(data){

                socket.emit('update',JSON.stringify(data));

            });

            ee.on('insert',function(data){

                socket.emit('insert',JSON.stringify(data));

            });

            ee.on('delete',function(data){

                socket.emit('delete',JSON.stringify(data));

            });
        });
    }

So my primary question/concern is that the amount of memory used for the closures will grow linearly with the number of socket connections and will never stop or decrease. Do socket.io disconnect events release memory via garbage collection?

It seems that I will need to reorganize the code above to accomplish two things:

  1. to allow for garbage collection so that the server memory footprint doesn't grow unboundedly

  2. to avoid publishing all the data for each and every socket connection, which is what it is doing now.

Is this accurate?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source