Use cases for WeakMap
brendan at mozilla.com
Mon May 16 13:07:44 PDT 2011
On May 16, 2011, at 11:30 AM, Erik Corry wrote:
> 2011/5/16 Andreas Gal <gal at mozilla.com>:
>> Even if you want to store weak-map specific meta data per object, nobody would store that directly in the object. Thats needlessly cruel on the cache since >>99.9% of objects never end up in a weak map. Instead one would locate that meta data outside the object in a direct mapped dense area (like mark bitmaps), which is on its own page that is not write protected.
> More than 99.9% of objects don't have a property called "fish".
> Nevertheless if someone adds a "fish" property to an object V8 will
> try to (and usually succeed in) storing it in the object and it won't
> be cruel on the cache. Quite the opposite.
That's true of JS using oneObj.fish among many, which is not the case we're arguing.
The case at hand is whether the GC has to fetch or store from an object (possibly a frozen object) used as a key in a WeakMap, to decide whether to treat the value part of the WeakMap entry as a strong reference. Touching random objects during GC is generally cache-cruel.
A GC may want to touch objects, even frozen objects, so long as this implementation detail can be concealed and performance is good.
Another JS implementation might want to avoid such key-object touching, and it might well want to write-protect frozen object memory. I said that and it seemed you thought such an implementation was impossible. We have one, but maybe there's more to discuss, a better way to GC weak maps.
Implementation issues are not the big deal here, though; this seems like a tangent. The main thread of discussion, as the Subject: says, was about use cases. WeakMaps have a strong use-case: mapping any object to per-object data that cannot be stored in the object -- in particular a membrane in the recursive pattern used for mediation, capability revocation, etc. between vats (windows, iframes, sandboxes, etc.).
This is the strongest use-case, IMHO.
There is a more generalized use-case for object-keyed indexing or memoization without memory leaks. Such indexes, memos, and caches, if implemented by strong maps, and if the key can be (reached from) a value and vice versa in the map, are terribly leak prone. Such caches generally don't need to be enumerated (except for debugging).
WeakMaps satisfy this more general non-enumerable object-keyed cache use-case well, too -- at least as far as I can tell. We'll be building on the Firefox nightly implementation to find out more.
More information about the es-discuss