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

David Bruant david.bruant at labri.fr
Wed May 11 11:16:56 PDT 2011


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);
  };
}
----
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

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20110511/bc198324/attachment.html>


More information about the es-discuss mailing list