Thoughts on WeakMaps
dherman at mozilla.com
Tue Jun 7 09:47:33 PDT 2011
[A propos of nothing, can I ask that you either change your font or use plain-text email? Your font shows up almost unreadably small in my mail client.]
> I'm currently working on the WeakMap documentation  and I have thought of two points:
> 1) myWeakMap.set(key, value) doesn't return anything. It could return the previous value for the key (if such a thing exists). Is it intentional that the set function doesn't return anything?
I don't have strong feelings about this, but I guess I have a mild preference for the way it's currently specified. I think it's useful as a rule of thumb to separate imperative actions from operations that are performed to compute a result. JS already violates this in a bunch of places, but I don't think consistency is sacrosanct here. OTOH, I don't think this is all that big of a deal.
> 2) The notion of weak reference as used in current WeakMap seems to be assuming that the garbage collector will work on whether objects are reachable or not. I have read (I thought it was the wikipedia page, but it apparently wasn't) that there is another notion for garbage collection which is whether an object will be used or not in the future. Of course, this notion is far more difficult to determine than reachability, but this is not my point.
> Let imagine for a minute that a lot of improvements is done in the field of object non-future-use. Will WeakMap be any different than a regular Map?
> If an engine is able to tell that an object will not be reachable, does it matter if there are remaining (soft or strong) references?
Correct me if I'm wrong, but I don't see how this would be observable. If your miracle-GC can predict that e.g. the key will never be used again, even though it's actually reachable, then it's able to predict that you're never going to look it up in the table. So even though the spec describes it in terms of reachability, your miracle-GC is not observably violating the behavior of the spec.
> The consequence of this second point is wondering whether it's a good idea to standardize WeakMap (instead of Map) at all.
I think this was already said in this thread, but just to be clear: WeakMap comes with different space, performance, and membership behavior than Map, and Map also exposes more operations (namely, enumeration) than WeakMap -- by design. WeakMap allows non-deterministic deletion of elements, so its operations are restricted to avoid leaking this non-determinism to programs. This is important both for portability and security.
IOW, WeakMap and Map are both there to serve different purposes and they carry different guarantees. We've discussed this in committee meetings before, but I want to make sure this is captured in public. We should also add verbiage to the proposals to make this clear.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the es-discuss