0

Say we have the code:

var players = [];

function Player(){
  var num = players.length;
}

players.push(new Player()); //player

Can I delete this player from memory? For example:

players.splice(0, 1);

Will garbage collector collect the player after this?

mqklin
  • 1,928
  • 5
  • 21
  • 39
  • 1
    If there are no other variables referring to the player, it will be collected. That's how automatic garbage collection works. – Barmar May 11 '15 at 17:16
  • For your reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management – karthick May 11 '15 at 17:20

1 Answers1

0

I recommend taking a look at Deleting Objects in JavaScript, When should I use delete vs setting elements to null in JavaScript? and Memory Management (nice reference, @Karthick).

Since Javascript is garbage collected, you don't need to delete objects themselves - they will be removed when there is no way to refer to them anymore.

You can, however, delete the reference to the object once you're certain it's been used:

It can be useful to delete references to an object if you are finished with them, because this gives the garbage collector more information about what is able to be reclaimed.

However this is in general taken care of for you and even if you hit an edge case it should not be a performance problem in small scale applications.

Community
  • 1
  • 1
Jonast92
  • 4,964
  • 1
  • 18
  • 32