WeakRef - proposal for adding to the ECMAScript standard
He wrote a small post in his telegram channel. I thought that it might be of interest to the readers of Habr.
Recently, an article on the V8 blog dedicated to the new WeakRef (Stage 3) prozal - "Weak references and finalizers".
I will try to explain in my own words its essence by example. Imagine that you have some kind of image processing in your browser, for example, a watermark is applied to them (I agree, the example is not very realistic), and then these images are somehow used. The watermark is superimposed by a function that intensively consumes the CPU. Images can be repeated, therefore, in order not to load the processor once again, we create a cache of images with a watermark in
Map, let the name of the image file be the key. But here a problem arises if some image will not be used by us, it will still be in memory, since the
Mapkey will refer to it (strong reference). Therefore to our
MapI didn’t eat up unnecessary memory, it is necessary to somehow determine such situations and clean the cache with my hands. This is not very convenient.
This is where WeakRef comes to the rescue. Using WeakRef, you can create a weak link to an image and write it 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 keys from Map in the proposal, it is proposed to use the additional FinalizationGroup API.
Interesting fact. At the very beginning of the article we give a small overview of the already included in the standard WeakMap and WeakSet. It turns out that the most formal name for the relationship used in WeakMap is Ephemeron.