How to determine if an object was garbage collected in Javascript?

I am creating a javascript game that creates a level object using var:

function start() { var myGameLevel = new Level(2); } 

This "Level ()" object has great functionality, primarily adding elements to the DOM and making them interactive. Simplification:

 function Level(i) { var _difficulty = i; this.init = function(){ jQuery("#container").append(...game elements here...); jQuery("#button").on('click', function() {...}); } } 

My question is: how can I find out if the level object created in the "start" function was garbage collected or not? I try to use only the "var" variables so that there are no external links. When the DOM is cleared of all game elements, I am an EXPECT level object that should be released from memory, but how can I be sure?

+6
source share
2 answers

Weak links are considered a security risk and, therefore, inaccessible to unprivileged code in browsers.

These problems do not apply to javascript running with privileged code or server, for example. through node.js, and therefore weak reference implementations of the platform may be available to them. firefox addons can use Components.utils.getWeakReference ()

WeakMap / WeakSet may be sufficient for certain programming patterns, but they do not allow the program to observe garbage collection, because this will require a key to examine these data structures, but holding this key will prevent the collection of objects in the first place.

An additional concern expressed by JS developers is that depending on how powerful hypothetical weak ref APIs can be. by offering notifications of completion - it can reveal significant volumes of behavior of the Civil Code, which, in turn, can limit future implementations, since a change in behavior can lead to disruption of web applications.


Update: Now it is a proposal to standardize weak references in JS, which mitigates perceived risks by linking the release of objects with low availability to JS, making the behavior more deterministic.

+5
source

I don’t think you can control javascript garbage collection. Typically, a variable or object can be assembled if there is no reference to it. Thus, you can increase your chances of collecting an object by developing your logic so that the object goes out of scope.

+3
source

Source: https://habr.com/ru/post/982611/


All Articles