Is WeakMap performance influenced by the Key Object?

Viewed 1136

When using a WeakMap Object in JavaScript, the get and set methods require a Key to be passed in as argument.

FYI, I'm using WeakMap to simulate private properties for a class, something like this:

window.MyObject = (function(){
  let _privateProperty = new WeakMap();
  class MyObject {
    constructor(value) {
      _privateVariable.set(this, value);
    }
    SamplePrivateGet() {
      return _privateVariable.get(this);
    }
  }
  return MyObject;
})();

My question is: is get and set performance influenced by the object used as key?

I know primitive types can't be used as key, but maybe using an object with only one property as key could be faster than using an object that has, say, one thousand properties.

I tried looking at ECMA specifications but it's not specified, my guess is it's because it would depends on the browser's implementation.

EDIT: There are two ways to approach this with WeakMaps, one is declaring a single _privateProperties WeakMap to which I will add my private properties, the other declare one WeakMap for each of the private properties. I'm currently using the second approach so that every WeakMap can be Garbage Collected separately, but maybe going with the first would allow me to make much less .get calls. But I guess that's out of the scope of the question :)

1 Answers

Not sure if this is good idea, but you could make kind of private instance properties by using Symbols.

const PRIVATE_VAR = Symbol('MY_CLASS::PRIVATE_VAR');
const PRIVATE_FUNC = Symbol('MY_CLASS::PRIVATE_FUNC');

export default class MyClass{ 
  constructor(value){
    this[PRIVATE_VAR] = value;
  }  
  [PRIVATE_FUNC](){ 
     /* ... */
  }
}

Without access to those Symbols values, it is quite hard to access those specific instance properties (plus instance properties defined with Symbols are non-enumerable in classes and objects).

btw 'Private instance methods and accessors' are at stage 3 so such solutions might not be relevant soon https://github.com/tc39/proposals

Related