title: Understanding object creation and garbage collection of a NodeJS WebSocket server
body: <p>I'm using the <a href="https://github.com/einaros/ws" rel="nofollow">ws</a> module in nodejs for a web socket server, and the simplified version of the code is this:</p>
  
  <pre><code>var WebSocketServer = require('ws').Server
  var wss = new WebSocketServer({port: 9001});
  
  wss.on('connection', function (ws) {
  
      // is the ws object created here ?
  
    ws.on('message', function (message) {
      if (message[0] === '+') {
          ws.name = message.substring(1);
          console.log(ws.name+' connected');
      }
    });
  
    ws.on('close', function () {
      console.log(ws.name+' disconnected');
      // Will this ws object be deleted ?
    });
  });
  </code></pre>
  
  <p>I would like to know:</p>
  
  <ul>
  <li>On each event of a connection, is a ws object created ? </li>
  <li>Does one of this object per connected client persist in RAM until it's garbage collected ?</li>
  </ul>
  
  <p>And most importantly:
  If tons of clients disconnect and the ws objects keep lying around until they are garbage collected, when the garbage collection happens, my server could be locked for quite some time right ? <strong>Should I go through the trouble of storing these ws objects in another object, so I could use the delete keyword and remove them as soon as I get the close event ?</strong></p>
  
  <p>If I were to do so, my could would be somewhat like this:</p>
  
  <pre><code>var WebSocketServer = require('ws').Server
  var wss = new WebSocketServer({port: 9001});
  
  var websockets = {};
  
  wss.on('connection', function (ws) {
    ws.on('message', function (message) {
      if (message[0] === '+') {
          ws.name = message.substring(1);
          websockets[ws.name] = ws; // Add to the object that stores ws objects
          console.log(ws.name+' connected');
      }
    });
  
    ws.on('close', function () {
      delete websockets[ws.name]; // Delete from the object
      console.log(ws.name+' disconnected');
    });
  });
  </code></pre>
  
  <p>So, is it worth it ? Am I writing more garbage collection friendly code in the second snippet ? Will it help avoid locking up for a long time when a garbage collection happens ?</p>
  
  <p><strong>UPDATE</strong>: I'm sorry I just realised how stupid the second snippet of code is. I'm actually duplicating the amount of objects when I do <code>websockets[ws.name] = ws</code>... But the first part of the question still remains valid.</p>