What is the reason behind Game code continuously running and not being garbage collected?
The misconception lies in the fact that even though the message appears to still be displayed, it doesn't mean that your game instance is actively using memory or executing its code. Once the message is set, the Game instance becomes eligible for garbage collection.
In reality, nothing within the code prevents the Game instance from being garbage collected. Sometimes, garbage collection may not occur unless certain conditions like memory pressure necessitate it. Modern engines such as V8 can optimize memory usage effectively without needing immediate garbage collection (for example, by allocating instances on the stack and then deallocating them once they are no longer needed).
Could references to the DOM influence the garbage collection process?
No, references from the game instance to the DOM elements do not hinder garbage collection of the game instance itself. The direction of the reference matters, and simply having references to the DOM elements from the game instance won't prevent garbage collection. Additionally, most retrieved references are not retained beyond their initial use.
Which type of code inside the Game class could halt the garbage collection of the instance?
Any code that establishes a direct or indirect reference to the game instance can impede garbage collection. For instance, modifying the instantiation of Game like:
window.myGame = new Game();
would create a property in the window object directly pointing to the game instance, thus preventing garbage collection. Similarly, adding code like the following within init can also obstruct garbage collection:
var self = this;
document.getElementById("message").addEventListener("click", function() {
this.innerHTML = self.name;
}, false);
This code creates multiple layers of references starting from the DOM element, through the event handler function, up to the context where Game instance resides.
It's important to note that while the Game function itself remains accessible due to the closure assigned to window.onload, the specific Game instance created temporarily under myGame is eventually removed during garbage collection.
When inspecting Chrome's heap snapshot, instances of Game (the function) can be found but not Game instances (objects) unless deliberately retained.
For reference, after analyzing your code in Chrome's heap snapshot feature, instances of Game were not detected initially. However, retaining the instance explicitly by assigning it to `window.myGame` confirmed its presence in the heap snapshot indicating potential hindrance to garbage collection.