3

I have memory leak in my js multiplayer game. I bind a lot of callbacks when client is connected to the server. My question is do i have to unbind callbacks before deleting socket from the table of players ?

Here is my sample callback:

 Player.prototype.viewPortListenerInit = function(){
  var self = this;

  this.socket.on('clientViewPortResize', function(data){
    self.clientViewPort = data;
  });

  };

Here is adding player to the list/hashset of players :

this.list[socket.id] = new Player(socket);

And here is deleting:

socket.on('disconnect', function(){
       delete this.list[socket.id]
});
peterSweter
  • 633
  • 6
  • 23
  • https://www.alexkras.com/simple-guide-to-finding-a-javascript-memory-leak-in-node-js/ I only skimmed this but it sounds like you probably forgot to remove all references to stuff. – Chris Rollins Dec 27 '16 at 17:00
  • What do you mean by "delete"? And from where will you unbind it? What you really need to do is remove the reference to the socket from where you trigger the events. – Bergi Dec 27 '16 at 17:11
  • I have list of players and i perform deleting like this: delete this.list[socket.id]; – peterSweter Dec 27 '16 at 17:16
  • Maybe you should post the code that adds and deletes from that list. I gave an answer assuming it was an array. – Chris Rollins Dec 27 '16 at 20:51
  • Are you sure you have removed all references to the Player object? – Chris Rollins Dec 28 '16 at 17:17

1 Answers1

2

When there are no references to instance EventEmitter (like socket), it's garbage collected with its callbacks.

Ginden
  • 5,149
  • 34
  • 68
  • Ok, but I have reference to the Player object inside this callback, and player object keep reference to socket. is it still be collected ? – peterSweter Dec 27 '16 at 19:43
  • 1
    if there are any references to an object it is not garbage collected – Chris Rollins Dec 27 '16 at 20:54
  • After deleting Player object from list of players there is no way to reach socket from the program, except from socket callback. Do I need to unbind this socket or make some kind of socket.disconect() ? – peterSweter Dec 27 '16 at 21:30
  • even if the reference is local to a certain function if that reference still exists it prevents garbage collection. not sure what you mean by from socket callback though. does a reference exist or not? – Chris Rollins Dec 28 '16 at 21:10
  • 1
    "_even if the reference is local to a certain function if that reference still exists it prevents garbage collection_" - garbage collection isn't as simple as reference counting - if callback function holds sole reference to an object, then callback function can be garbage collected and then object is garbage collected too. So you don't have to unbind your callbacks and I recommend to use other techniques to trace memory leak - read articles like: https://blog.risingstack.com/finding-a-memory-leak-in-node-js/ – Ginden Dec 29 '16 at 08:02