WeakMaps question ?

Kris Kowal kris.kowal at cixar.com
Fri Nov 11 15:37:04 PST 2011


On Fri, Nov 11, 2011 at 3:28 PM, Irakli Gozalishvili <rfobic at gmail.com> wrote:
> I really need to know why WeakMaps don't accept primitives as keys, can
> anyone please reply ?

It’s because WeakMaps are intended to drop values if the key is
garbage collected.

A WeakMap guarantees that it will drop its value if it becomes
provably inaccessible.

This works for non-primitive keys because we can guarantee that once
an object has been garbage collected, no future object can be created
that would have been identical to it, making the value inaccessible.

Once a primitive value like 1 or the string "abc" has been garbage
collected, it is trivial to construct a new value that is identical to
the original key, so we could never implicitly garbage collect the
value corresponding to a primitive key.

Mark Miller has proposed a strong variation of WeakMap, simply Map,
that would serve well in cases where items are explicitly collected.

http://wiki.ecmascript.org/doku.php?id=harmony:simple_maps_and_sets

As I recall, a variant of Map was considered in the ES4 timeline as well.

Kris Kowal


More information about the es-discuss mailing list