Question about closing / encapsulation efficiency in JavaScript

I'm a little new to JavaScript, so bear with me if this is a dumb question.

Let's say that I have a class that looks like this:

var obj = function () { var val; return { setVal: function(newVal) { val = newVal; }, getVal: function() { return val; } }; }; 

Assuming my syntax is correct, it defines a class with the property "private" with the name "value" with methods for setting / getting the property. Now I will create two objects from this class:

 var myObj = obj(); var yourObj = obj(); 

Does it create a separate setVal () and getVal () method for each object? If not, why not? If so, is this a serious concern when building effective web applications? Is a compromise (if any) effective for closing it in most / all contexts? I'm dumb?

Thanks Gerard

+8
performance javascript closures oop
source share
2 answers
 var obj = function () { var val; return { setVal: function(newVal) { val = newVal; }, getVal: function() { return val; } }; }; 

what this function does is the following:

  • create a variable named val
  • create new object
  • create a new function and assign it to the setVal field
  • create a new function and assign it to the getVal field
  • return an object.

So, you always create 4 new things.

This is not a problem if the page has less than 1000 objects. Refactoring is micro-optimization.

An alternative would be to not rely on local variables and use this._val to indicate that val is private.

+3
source share

He does it conceptually. However, since this is such a common picture, modern JavaScript JIT developers know how to optimize it, so there is only one copy of the code stored in memory with the appropriate pointer redistributions to make it work with the corresponding closure.

EDIT: although I am not very good at source code, here are some basic proofs. Download the Chrome dev channel release and take heap snapshots before and after running the following code:

 var obj = /* as above */; var objs = []; for (var i = 0; i < 10000; ++i) { objs.push(obj()); } 

Then do the same for this code:

 function Obj() { } Obj.prototype.setVal = function (value) { this._val = value; }; Obj.prototype.getVal = function () { return this._val; }; var objs = []; for (var i = 0; i < 10000; ++i) { objs.push(new Obj()); } 

In both cases, you will find heap snapshots to show the same numbers for the "Code", so the optimization that I describe is really described.

0
source share

All Articles