A partial archive of discourse.wicg.io as of Saturday February 24, 2024.

Weak Values in JS

pixelcort
2014-06-20

It is sometimes useful to maintain an identity map of objects in JavaScript, but then it becomes unclear when it is safe to dereference them when nothing has used them in awhile.

One solution is to introduce weak values in JS, so an object wouldn’t keep its values around forever.

jonathank
2014-06-20

@pixelcort what are the use cases for this above what is set out in WeakMaps: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap

domenic
2014-06-20

Yes, this is the exact use case for WeakSets and WeakMaps, which are notably shipping in every browser (except maybe Safari 7?)

pixelcort
2014-06-20

As I understand it, WeakMaps and WeakSets behave the opposite of what would be needed to make an identity map. That is, a WeakMap has weak keys, not weak values.

The use case is this: you want to only have one instance of each model object per primary key. But, if nothing is referring to an instance, you’d like it to be garbage collected. So ideally you’d like some way to refer to these model instances, such that you wouldn’t accidentally instantiate another with the same primary key.

If there is a way to do this with WeakSet or WeakMap, I’d love to know.

domenic
2014-06-20

Both keys and values are held weakly in a weak map.

tabatkins
2014-06-20

To be specific, the key has a strong reference to the value, so as long as the key is reachable, you can always get the value back out. (It won’t GC out from under you.)

But yeah, if the key ever GCs, the value is then (a) unreachable from the WeakMap, and (b) GCable as long as there are no other references.

Note that the key has to be an object; primitives can’t be used, as they get collected and regenerated transparently constantly, and so don’t have a coherent sense of “identity” to base the key->value ref off of.

fflorent
2014-08-03

One solution is to introduce weak values in JS, so an object wouldn’t keep its values around forever.

Aren’t you looking for weak references?

http://wiki.ecmascript.org/doku.php?id=strawman:weak_references

http://wiki.ecmascript.org/doku.php?id=strawman:weak_refs

Florent

pixelcort
2014-08-03

Ah yes, weak references would work perfectly; thanks @fflorent!

fflorent
2014-08-03

You’re welcome.

AFAIK, it is (was?) being debated (lots of questions have been raised regarding GC if I am not wrong). But some people here may answer more precisely here ;).

Florent