Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can this function be garbage-collected?

Consider this piece of cake... ehm, code:

'use strict'

function doWork () {
  return new Promise(function (resolve, reject) {
    // work work work...
    // Done! But... where's the resolve() ???
  })
}

doWork().then(function doMoreWork () {
  // Some more work to do...
})

Once the function in the Promise's constructor finishes...

  1. Is the Promise object garbage-collectible?
  2. Is doMoreWork() garbage-collectible?

My guess is that doMoreWork() cannot be GC-ed directly because the Promise keeps a reference to it, but once the promise's body finishes and returns the execution context to the upper (?) scope, the stack unwinds (because there is no more statements here to be executed) and the Promise becomes unreachable, thus being garbage-collectible.

Can you confirm that my understanding of this topic is correct?

How could I empirically observe this behaviour? In other words, how can I monitor what objects are being GC-ed and when? I develop purely in Node.js, if that makes any difference.

like image 428
Robert Rossmann Avatar asked Mar 30 '15 08:03

Robert Rossmann


People also ask

Which function is used for garbage collection?

The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is found in System and Runtime classes.

Which objects are garbage collected?

An object is eligible to be garbage collected if its reference variable is lost from the program during execution. Sometimes they are also called unreachable objects. What is reference of an object? The new operator dynamically allocates memory for an object and returns a reference to it.

What is garbage collection example?

The main objective of Garbage Collector is to free heap memory by destroying unreachable objects. The garbage collector is the best example of the Daemon thread as it is always running in the background.

What is garbage collection?

Garbage collection (GC) is a memory recovery feature built into programming languages such as C# and Java. A GC-enabled programming language includes one or more garbage collectors (GC engines) that automatically free up memory space that has been allocated to objects no longer needed by the program.


1 Answers

There is nothing keeping reference to the promise so it will be garbage collected. The promise is the only thing keeping reference to the function doMoreWork so it will be garbage collected too.

How could I empirically observe this behaviour? In other words, how can I monitor what objects are being GC-ed and when? I develop purely in Node.js, if that makes any difference.

The GC in V8 never necessarily collects an object. For instance if this is your whole program, it would be a waste of time to run any GC in the first place.

like image 145
Esailija Avatar answered Sep 21 '22 15:09

Esailija