Proposal: Abstract References

Andrea Giammarchi andrea.giammarchi at gmail.com
Wed Oct 22 07:34:42 PDT 2014


I was trying to actually use same amount of indirections, since that's
probably more likely how real code might look like but you are right, hand
crafting per each case the pattern we have a different winner, which is the
single WeakMap instead of the multiple one.

I guess the reason is the double x/y.set and x/y.get VS only one, here the
new bench:
http://jsperf.com/abstract-reference/2

and here the hand crafted code:

```js
var result = [];

// Multiple WeakMaps approach
var PrivateCoordinatesMWM = (function () {

  var
    _x = new WeakMap,
    _y = new WeakMap
  ;

  function PrivateCoordinatesMWM(x, y) {
    _x.set(this, x);
    _y.set(this, y);
  }

  PrivateCoordinatesMWM.prototype.toString = function toString() {
    return ''.concat(
      '[', _x.get(this), 'x', _y.get(this), ']'
    );
  };

  return PrivateCoordinatesMWM;

}());

// Single WeakMap approach
var PrivateCoordinatesSWM = (function () {

  var _wm = new WeakMap;

  function PrivateCoordinatesSWM(x, y) {
    _wm.set(this, {x: x, y: y});
  }

  PrivateCoordinatesSWM.prototype.toString = function toString() {
    var _pvt = _wm.get(this);
    return ''.concat(
      '[', _pvt.x, 'x', _pvt.y, ']'
    );
  };

  return PrivateCoordinatesSWM;

}());
```

Regards


On Wed, Oct 22, 2014 at 2:46 PM, Andreas Rossberg <rossberg at google.com>
wrote:

> On 22 October 2014 14:18, Andrea Giammarchi <andrea.giammarchi at gmail.com>
> wrote:
> > FWIW the Multiple WeakMaps approach seems to be 2X ( Chrome ) up to 3X (
> FF
> > Nightly ) faster than single WeakMap approach but I don't know how much
> > WeakMap instances cost in terms of GC operations so this bench might be
> very
> > pointless ( and surely it's premature )
> >
> > Weirdly enough, Chrome Canary seems to be able to optimize the single
> > WeakMap approach pretty well, with a gap of 1.25X faster perfs on
> multiple
> > WMs.
>
> If you really want to micro-benchmark, then perhaps at least use more
> reasonable code that avoids unnecessary indirections distorting the
> results. That is:
>
> ```js
> var PrivateCoordinatesMWM = (function () {
>   var x_ = new WeakMap
>   var y_ = new WeakMap
>
>   function PrivateCoordinatesMWM(x, y) {
>     x_.set(this, x)
>     y_.set(this, y)
>   }
>
>   PrivateCoordinatesMWM.prototype.toString = function toString() {
>     return ''.concat('[', x_.get(this), y_.get(this), ']')
>   };
>
>   return PrivateCoordinatesMWM
> }())
> ```
>
> This also happens to be more readable. ;)
>
> /Andreas
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20141022/7a711786/attachment.html>


More information about the es-discuss mailing list