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

Mike Samuel mikesamuel at gmail.com
Thu May 12 16:19:47 PDT 2011


2011/5/11 David Bruant <david.bruant at labri.fr>:
> Hi,
>
> I've recently been thinking about the case of memoizing. Let's assume that a
> function f takes an object o as a parameter and that f is a pure function
> (results only depends on argument).
> ----
> function f(o){
> /* perform a computation, return the result */
> }
> ----
>
> 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);
>   };
> }

Does this do what you were trying to accomplish with has, but without
requiring has?

function memoizer(f){
  var cache = WeakMap();
  // Used in cache to distinguish undefined value but known from
  // undefined.  Does not escape, so cannot be returned by f.
  var undefSubstitute = {};
  return function(o){
    var res = cache.get(o);
    if (res === void 0) {
      res = f.apply(this, o);
      cache.set(o, res === void 0 ? undefSubstitute : res);
    } else if (res === undefSubstitute) {
      res = void 0;
    }
    return res;
  };
}




> ----
> But as you can see, this implementation requires a .has method.
> harmony:weak_maps shows how to implement has (and delete) on top of "get"
> and "set", but this comes to the cost of an object per WeakMap (well,
> actually, the same mascot could be factorized out and used for all
> ExplicitSoftOwnField) and the cost of being a non-native implementation.
>
> As an argument to add delete to the API, I'd say that it will be an
> encouragement for people to remove keys from the weak map. In the design of
> WeakMap is written: "for each mapping k ⇒ v in a reachable weak map m, if k
> is reachable then v is reachable". If people see that the API is "get+set",
> they won't think of memory at all, while if they see a "delete" method in
> the API, they are more likely to wonder why it's here and understand that
> they should use it to free memory up. This is, of course, nothing else than
> a guess.
>
> David
>
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
>


More information about the es-discuss mailing list