If I can't avoid using the "new" keyword in my Node.js app, how can I efficiently mark the object for garbage collection? I create a new object with a fairly high level constructor (by that, I mean new myObj()
actually creates several new Something()
objects deeper down in the process.
Let's say my constructor looks a little like the following:
function User(name, age) {
this.something = x;
this.greet = function() { return "hello"; };
this.somethingElse = new OtherThing();
return this;
}
Then I create a new User
within another function:
function createUserAndGreet(name, age) {
var user1 = new User(name, age);
user1.greet();
// now I don't need user1 anymore
}
(btw, I know this code sucks but I think it gets my point across)
After I have got him to greet, how can I then get rid of him and free up the memory he occupied?
So if I just set user1 to null with user1 = null;
after I'm finished with him, will he be gone forever and GC will come and clean him up? Will that also delete the new OtherThing()
that was created? Or is there something else I need to do? I hear that using new
is notorious for memory leaks so I just want to know if there's a way around this.
The GC takes care of everything that is not referenced. So your code "GC-Compatible" as is, because after the call to the "createUserAndGreet" function, all references are destroyed.
The only things you have to care about for the GC is what is attached directly to the Window object (globals), these will never be collected, but your two variables are scoped inside the "createUserAndGreet" function, and this scope is destroyed when the function call ends.