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...
Promise
object garbage-collectible?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.
The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is found in System and Runtime classes.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With