Questioning WeakMap.prototype.clear

David Bruant bruant.d at
Tue Jan 22 03:56:07 PST 2013

Le 22/01/2013 11:47, Jason Orendorff a écrit :
> On Mon, Jan 21, 2013 at 6:04 AM, David Bruant <bruant.d at 
> <mailto:bruant.d at>> wrote:
>     [...] WeakMap.prototype.clear questions the property that was true
>     before its adoption ("you can only modify a weakmap entry if you
>     have the key")
> David, would you please elaborate your argument for this invariant? 
> This the first I've seen it stated.
> An invariant can be a powerful thing. Still, I guess my default 
> position is that (1) the object-capabilities perspective is only one 
> view among many; (2) even looking at things with an eye for o-c 
> integrity and security, clearing a data structure seems like a 
> reasonable thing to allow, treating a reference to the data structure 
> itself as a sufficient capability. It's (2) that I would especially 
> like you to address.
I think Rick already suggested your (2), though phrased a bit 
differently [1] (that was his #1). I answered [2]: "I thought more about 
how I use weakmaps and [well-encapsulate my weakmaps so that I'm the 
only holder] is a thing I do naturally indeed."
The problem may arise when you start sharing weakmaps around and some 
use cases require you to [3].

Regarding your (1), I don't doubt the need to clear a data structure 
since Allen explained a very compelling use case for that [3].
However, Mark showed an elegant way to implement .clear on top of 
clear-less weakmaps and the class syntax [4][5] (reproducing here the 
final version for clarity)

     // note: implements the WeakMap API but does *not* extend WeakMap.
     class WeakMapWithClear {
         private let wrapped;
         constructor() {
             wrapped = new WeakMap();
         get(key) => wrapped.get(key),
         set(key, val) => wrapped.set(key, value),
         has(key) => wrapped.has(key),
         delete(key) => wrapped.delete(key),
         clear() { wrapped = new WeakMap(); }

Now, the only thing that can differentiate both the native against this 
version is performance I think. Allen seems to argue that a native 
.clear would have better perf characteristics (related to GC). I still 
fail to see why the difference would be significant (but I need to 
re-read his recent posts about that).
In all likelihood, .clear is a method that is used sporadically. At 
least, one needs to fill up the weakmap a bit before calling it, so I 
don't think a marginal perf difference would matter.

As an implementor, what is your feeling about performance 
characteristics of both the native and the class-based version?


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the es-discuss mailing list