2 ms·
I was confused by his description of WeakMap, because I hadn't looked at the spec in a while. For reference, the reason why it's not applicable to the task at h
by himinlomax 6y ago
I was confused by his description of WeakMap, because I hadn't looked at the spec in a while. For reference, the reason why it's not applicable to the task at hand is because it's not primarily meant to have the values weakly referenced. Rather, it's meant to not lock the keys in. I'm not sure what he means by "best used to link objects together". WeakMap simply allows you to keep data about an object outside of it and without keeping it from being freed when it's not needed anywhere else.
- sfink 6y agoThat's what he means by linking objects together. Though I would describe it as you did; WeakMaps are normally used for associating data with an object, without having the WeakMap entry itself keep the object (aka the WeakMap key) alive. If the object goes away otherwise, the entry will go with it. (Or if the WeakMap goes away, then all of its entries will go away at once.) In terms of "liveness", a WeakMap entry is an "and" edge between the key and the map: the entry is only kept alive if both the key and map are still alive. (And the entry keeps the value alive, though it may not be the only thing doing so.) WeakMaps (ephemeron tables) were designed specifically to make garbage collection not be observable, for the reasons jgraham described above. If you really want to know, such as for testing, then WeakRef and FinalizationRegistry are the newer ways to do this. But know that if your app needs this stuff as part of its normal functioning, then there's at least a 90% chance you're doing something wrong. The GC does not run because you think it should run. If anything, it tries to not run, as much as possible. And the more we optimize it, the better it will get at not running. "Running slow code" is worse than "running fast code" is worse than "not running code at all". (source: I work on the SpiderMonkey GC engine.)