Add enumeration methods (and clear) to WeakMap and WeakSet

Since WeakRef has been introduced it is now possible to create enumerable weak collections (one example in WeakRef Proposal). However since they are not built-ins they require the addition overhead of creating multiple private collections to back the storage and a finalizer to clear it.

I propose that WeakMap/WeakSet match the full api of Map/Set. Adding: clear, Symbol.iterator, entries, keys, values.

Would their be any reasons not to do this, such as possible reductions in performance for existing WeakMap and WeakSet?

1 Like

I do think supporting these methods would decrease the performance of WeakMap and WeakSet. So should perhaps be added as a new separate class? new EnumerableWeakMap. Right now v8 implements WeakMap/Set by storing the hash in the key Object itself, so there is no direct way to go from the WeakMap/Set back to the object without searching all objects for one with a matching hash.

There are also some details about possible secuirty implemations of enumerable WeakMap/Set

A key property of Weak Maps is the inability to enumerate their keys . This is necessary to prevent attackers observing the internal behavior of other systems in the environment which share weakly-mapped objects. Should the number or names of items in the collection be discoverable from the API, even if the values aren't, WeakMap instances might create a side channel where one was previously not available.

1 Like

The performance implications are a concern, so new EnumerableWeak classes seems the best option.

As far as security goes WeakMap/Set methods can already be overridden to allow 3rd party observation. Either you need to freeze the instance and it's prototype, or not expose the WeakMap/Set directly, by using wrapper functions for setting and retrieving values. The second of which would still be a good option for enumerable collections.

1 Like

Or, you can preserve and call-bind the prototype methods in advance.

That you can modify the prototype doesn't change that it's critical that WeakMap and WeakSet never expose the keys or members unless you already have them.

1 Like