Weak Values in JS


#1

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.


#2

@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


#3

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


#4

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.


#5

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


#6

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.


#7

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


#8

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


#9

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