Do primitive values ​​need to be nullified to collect collectors?

If I have the following code:

function MyClass() { this.data = { // lots of data }; } var myClassInstace = new MyClass(); var myobj = { num:123, str:"hello", theClass:myClassInstance }; 

I know this is absolutely necessary to do:

 myobj.theClass = null; 

To free myClassInstance and its data property for GC. However, what should I do with myobj.num and myobj.str ? Should I give them null too? Is the fact that they are primitive will change anything with respect to the GC?

+5
source share
3 answers

JavaScript runtime implementing garbage collection will be able to collect elements as soon as the values ​​are no longer available from the code. This is true for object references, as well as for primitives. Details of the exact moment when the element is assembled vary depending on the implementation, but you don’t even need to set the object references to zero (when you specify) if you do not need the object cleared before the natural completion of the current function.

All this is connected with the fundamental concept of the “sphere of action” and the “chain chain”. When an element is no longer in any chain of objects of other objects, it can be assembled. Understanding this will clearly answer this question, and will also help to understand closures, which are scenarios when elements remain in memory longer than you might expect.

+3
source

Here, a lot of "depends", starting from what your code does for the browser in which you work. However, if your JIT object is compiled so as not to use the map for its attributes, then the number must be an 8-byte double stored inline inside the object. Dropping does nothing.

The string and myclass instance will be a pointer to memory allocated outside the object (since the string can be too many bytes, it cannot be stored inside the object. The compiler can apparently store one instance of the string in memory and never free it, however) . Disabling them may allow the garbage collector to free them before the main object goes beyond.

However, the real question is why are you worried about this. If you did not profile your code and did not detect garbage collection or memory leak as a problem, you should not try to optimize the behavior of the GC. In particular, if your myobj object itself will live for a long time, you should not worry about resetting the fields. GC will collect it when it goes beyond.

+1
source

an undefined value (but not null) will work, however delete best example delete myobj.theClass

Just to avoid confusion, I will say that there is no way to really remove an object from memory in JavaScript. you remove links or set them to undefined so that the GC can work and really delete.

0
source

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


All Articles