Introduction: garbage recycling mechanism is seldom encountered in the job, see ruan yifeng’s book is written, recorded.
Garbage collection mechanism and WeakSet (1) Garbage collection mechanism only considers the strong reference of the object. (2) Garbage collection mechanism relies on “reference count”. When the count is 0, GC will automatically recover the memory occupied by the object. (3) When forgetting to dereference (a= NULL), memory cannot be freed, resulting in a memory leak.
WeakSet objects are weak references, that is, garbage collection mechanism does not consider WeakSet’s reference to the object, that is, if other objects no longer reference the object, then garbage collection mechanism will automatically recover the memory occupied by the object, not considering the object still exists in WeakSet.
This is because the garbage collection mechanism relies on reference counting and does not free the memory if the number of references to a value is not zero. After you finish using the value, you sometimes forget to dereference it, causing memory to be unable to be freed, which can lead to a memory leak. WeakSet references are not included in the garbage collection mechanism, so there is no problem. Therefore, WeakSet is suitable for temporarily storing a group of objects and information bound to the object. As soon as the object disappears externally, its reference in WeakSet disappears automatically.
Due to the above feature, a WeakSet member is not suitable for reference because it will disappear at any time. In addition, because the number of internal WeakSet members depends on whether garbage collection mechanism is running, the number of members may be different before and after operation, and when garbage collection mechanism is running is unpredictable, so ES6 stipulates that WeakSet cannot be traversed.
Reference: es6.ruanyifeng.com/#docs/set-m…
(after)