Argument in favor of adding "has" in the WeakMap API

felix felix8a at gmail.com
Wed May 11 11:38:43 PDT 2011


On Wed, May 11, 2011 at 11:16, David Bruant <david.bruant at labri.fr> wrote:
> A memoizer could be written to improve f time performance (by the cost of
> memory, of course).
> ----
> function memoizer(f){
>   var cache = WeakMap();
>   return function(o){
>     var res;
>     if(WeakMap.has(o))
>       return cache.get(o);
>     res = f.apply(this, o);
>
>     cache.set(o, res);
>   };
> }
> ----

I'm not sure I understand your code.

it's not clear to me why you need .has at all, since you can check the
return value of .get instead.  in the case where 'undefined' is a
valid value that you would want to memoize, you can store a unique
object to represent 'undefined'.

also, memoization is usually caching on argument values rather than
argument identity, but weakmap lookups are by object identity not
object value.  You can't use non-object keys in a weekmap, so in order
to gain the benefits of the memoization above, a caller would have to
be careful to avoid constructing new objects with the same values, and
somehow keep re-using the same argument objects, which is pretty
inconvenient for typical uses of memoization.


More information about the es-discuss mailing list