Javascript private methods — what is the memory im

2019-05-12 18:01发布

I'm working on a bit of code where I'm attempting to hide some private variables inside closures. The thing is the environment is fairly constrained in terms of memory, so I'm also concerned with keeping the overall footprint of the classes low.

What is the impact of using closures to hide private instance variables and methods when compared to just making all methods and variables on an object public? Would an instance of the one using closures take up more memory than an instance that did not use closures? If so, how much more memory would I expect to use?

my code would look like this

function Foo() {
   // private variables
   var status = 3;
   var id = 4;
... 
...

   // private methods
   var privateMethod = function () {
      // do something awesome
   }
   ...

   // a whole bunch of these


   // public methods

   this.publicDriver =  function () {
        privateMethod();
   }
    .. a few more of these

};

Versus

function Bar() {
   // only define public variables
   this.x = 1;
   this.y = 3;
}

Bar.prototype.method1 = function () { 
// blah;
}

.... Going on and defining all the rest of the methods.

4条回答
趁早两清
2楼-- · 2019-05-12 18:11

The fact that variables enclosed in a closure can be updated from outside the closure in JavaScript, would suggest that there only ever exists one copy of the variable. Which means that there's no reason why there should be any significant memory impact of using closures in JavaScript.

If the values of the variables were frozen once the closure was created, that would be a different story since it would mean that each closure would have to have a private copy of its enclosed variables.

All that being said, you should still perform the actual benchmarks to check :-)

查看更多
The star\"
3楼-- · 2019-05-12 18:15

Okay, so from what I can see, constructing the class using the closure case constructs new function objects for each method defined within the constructor, while the prototype assignment way creates a central function that is shared by all instances of the objects. The central instance is then interpreted per object for the proper instance variable references.

I'm guessing each function defined in the closure example refers back to the same stack frame.

Still, in my case, it's a lot more objects floating about.

查看更多
祖国的老花朵
4楼-- · 2019-05-12 18:20

Check out these benchmarks. Although they are inheritance benchmarks, it should give you an idea of the memory impact since some of them uses closures, and some don't.

查看更多
太酷不给撩
5楼-- · 2019-05-12 18:28

The following link shows information about some tips for profiling javascript functions to see information about their performance:

http://ejohn.org/blog/function-call-profiling/

查看更多
登录 后发表回答