0

Actually I am confused. Is a variable become candidate for GC after a success response or after sending stream to output device in NodeJS? For example

var myObject = new myClass(),
    xmlString = myObject.getXmlString();

res.write(xmlString); 
res.end();

if not then How to GC this object or make myObject a candidate for GC?

Nur Rony
  • 7,823
  • 7
  • 38
  • 45

2 Answers2

2

Garbage collection generally depends on the references to the object, or lack there of. The object created by new myClass() can be collected once myObject no longer references it.

If myObject is declared within a function, it will typically be deleted when execution reaches the end of a function.

function foo() {
    var myObject = new myClass();
} // `myObject` doesn't exist beyond this

If you want to speed it along, you can assign myObject a different value or delete it:

myObject = null;

delete myObject;

For more info, see "What is JavaScript garbage collection?"

Community
  • 1
  • 1
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
1

Example:

var someString = 'hi there';

someString = 'not hi there any more';

The memory occupied by 'hi there' is elligible for garbage collection the second you assign something else to it, namely 'not hi there any more'. Now let's say that you know you're not going to use 'hi there' again, but don't have another handy string to assign to it, you can just 'delete' it.

var someString = 'hi there';
delete someString; 

The delete, in this case invalidates the object that 'someString' references, though doesn't necessarily free the memory immediately. This just helps the garbage collector know that you are done with the someString variable, despite the fact that it is still in scope. Perhaps because it was used as initialization for some closure or something like that.

Note: The use of the 'new' keyword does not change the logic above.

MobA11y
  • 18,425
  • 3
  • 49
  • 76