Skip to content
Advertisement

Do get accessors incur a per-instance allocation cost?

Say I have a class defined like this:

class Test {
  get a() { return 1; }
  get b() { return 2; }
  get c() { return 3; }
  get d() { return 4; }
  get e() { return 5; }
  get f() { return 6; }
  get g() { return 7; }
  get h() { return 8; }
}

And then I create several instances like so:

let a = new Test();
let b = new Test();
let c = new Test();

Are these get accessors allocated for each instance? That is, would the memory usage of each of those objects increase if I were to add more get accessors, or are the get accessors allocated once and simply shared amongst all the instances?

I tried testing it out with Chrome’s heap snapshot, and it seems like regardless of how many get accessors that I add that the memory usage of the object is the same, but I’m not sure if this is always the case, or under which conditions it holds.

I am wondering this because I am developing a browser game where memory allocation is relevant.

Advertisement

Answer

(V8 developer here.) Accessors, like other methods, are stored per-class, not per-instance. As long as you use classes in the usual way, it’s hard to accidentally get this wrong.

You can, of course, defeat this mechanism by explicitly storing function instances on each instance, e.g. if you use traditional/ES5 non-class constructor functions and write:

function MyObj {
  this.field = 42;
  this.method = function method(x) { ... }
}

var o1 = new MyObj();
var o2 = new MyObj();  // Fresh copy of `method`.

(Of course, in those days it was recommended to use MyObj.prototype.method = function() {...} instead.)
With classes, if you did similar assignments in the constructor, you’d get the same effect.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement