Hank Phung
Hank Phung

Reputation: 2149

In JS/NodeJS what will happen to an object when it been removed from an array?

I want to run an array of neural network trainers, it's running on an infinite loop like this:

Trainer.prototype.tick = function(){
  // do the try something and record the score
  setTimeout(function(){
    this.tick()
  },0);
}

So far it doing well but when I want to renew the training data and the neural networks, I will delete the trainer instance from my array and replace with a new instance. So the question is will it really delete the old instance and free up the memory?

Upvotes: 0

Views: 55

Answers (1)

jfriend00
jfriend00

Reputation: 707198

Javascript is a garbage collected language. That means that it automatically removes objects from memory when no active, reachable code still has a reference to the object. So, if you remove the object from an array and no other variable or property in your code has a reference to that object, then the object will be eligible for garbage collection and the system will free the memory that it occupies.

While your setTimeout() is active, there is still a reference to your object so it can't be garbage collected until the setTimeout() fires. But, since you're using a timer value of 0, the timer will fire very soon and that particular reference to the object will be cleared.

But, your setTimeout() immediately tries to call this.tick(). If that call succeeded, it would set another setTimeout() so it will never stop and will never be garbage collected. You'd have to stop setting new timers for it to be garbage collected.

But, in the code you show, the value of this will not be pointing at your Trainer object so the call to this.tick() will fail and no new timer will be set and as soon as the setTimeout() runs and the this.tick() call fails, the object will be ready for garbage collection.

Upvotes: 2

Related Questions