xiaoyi
xiaoyi

Reputation: 6741

Will javascript private members in classes cause a huge memory overhead?

In JavaScript, fields of an object are always "public":

function Test() {
  this.x_ = 15;
}
Test.prototype = {
  getPublicX: function() {
    return this.x_;
  }
};
new Test().getPublicX();       // using the getter
new Test().x_;                 // bypassing the getter

but you can simulate a "private" field by using a local variable, and using a closure as the getter:

function Test() {
  var x = 15;
  this.getPrivateX = function() {
    return x;
  };
}
new Test().getPrivateX();       // using the getter
// ... no way to access x directly: it's a local variable out of scope

One difference is that with the "public" approach, each instance's getter is the same function object:

console.assert(t1.getPublicX === t2.getPublicX);

whereas with the "private" approach, each instance's getter is a distinct function object:

console.assert(t1.getPrivateX != t2.getPrivateX);

I'm curious about the memory usage of this approach. Since each instance has a separate getPrivateX, will this cause a huge memory overhead if I create, say, 10k instances?

A performance test on creating instances of classes with private and public members:

Jsperf

Upvotes: 11

Views: 1015

Answers (1)

Konstantin Dinev
Konstantin Dinev

Reputation: 34895

Of course it would create memory overhead. In the public case your function belongs to the prototype not to the instance, which means there is only one instance, unless you specifically give a specific object it's own instance of that function. In the private case the function belongs to the instance which means that you need to perform memory management.

What I mean by this is the following:

var t1 = new Test();
t1.getPublicX = function () {
    return true;
}

var t2 = new Test();

t1.getPublicX(); // Returns true
t2.getPublicX(); // Returns 15

So you can end up in the same situation with public members as well. In general the answer to your question is: Yes there is a memory overhead when instantiating a large number of objects.

I should also add that the notion of public and private in javascript is not at all the same as in C++. In C++ private encapsulates the member for access only from within the class, which in javascript you can still access the member from anywhere.

And still after running a short test the overhead is in fact insignificant. The tab takes 40mb more (with google loaded) than without it as show in the screenshot below:

enter image description here

Link to full size image.

Upvotes: 6

Related Questions