📜 ⬆️ ⬇️

WeakRef - proposal for adding to ECMAScript standard

I wrote a small post in my telegram channel. Thought it might be interesting to Habr's readers.


Recently, an article on the V8 blog devoted to WeakRef (Stage 3) - "Weak references and finalizers".


I will try to explain in my own words its essence with an example. Imagine that some kind of image processing takes place in your browser, for example, a watermark is superimposed on them (I agree, the example is not very realistic), and then these images are somehow used. The watermark is superimposed by a function that consumes the CPU intensively. Images can be repeated, therefore, in order not to load the processor once again, we create a cache of images with a watermark in the Map ; the key is the name of the image file. But here a problem arises, if some image will not be used by us, it will still be in memory, since the Map will refer to it by a key (strong reference). Therefore, in order for our Map not to wipe out excess memory, it is necessary to somehow determine such situations and clean the cache with our hands. This is not very convenient.


This is where WeakRef comes to the rescue. With WeakRef, you can create a weak link to an image and write it down by key instead of the image itself:


 const wr = new WeakRef(image); cache.set(name, wr); //    const ref = cache.get(name); const image = ref.deref(); 

In this case, the garbage collector will be able to independently determine situations when the image in the cache is no longer needed and clear the memory. To clear the keys from the Map in proposal, it is proposed to use the additional API FinalizationGroup.


Interesting fact. At the very beginning of the article a small overview is given of those already included in the standard WeakMap and WeakSet. It turns out that the most formal name for the relationship used in WeakMap is Ephemeron.


https://v8.dev/features/weak-references


')

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


All Articles