Anonymous function storage performance

Suppose I create a factory object as follows:

var newObj=function(x){ var obj=[] obj.x=x obj.add=function(n){ return this.x+n } return obj } 

Now suppose I create hundreds of instances of this object:

 var obj1=newObj(1) var obj2=newObj(2) ... 

Each object obj1, obj2, ... stores its own copy of obj.add or do they all contain a link to a single instance of obj.add stored in memory?

Thanks!

+7
performance javascript anonymous-function
source share
2 answers

Both obj and obj2 will create their own copies of obj.add . These are functional expressions that are executed during creation and storage in memory during the whole life of an object.

If you want to maintain performance, then you should use prototyping :

 var newObj=function(x){ this.obj = []; this.obj.x = x; return this.obj; } newObj.prototype.add = function(n) { return this.obj.x += n; } 

This will create a function that all future newObj objects will use without taking up extra memory space for the same function.

+2
source share

All of them will have their own instances of this method.

If you use prototypes , they will pass this method if you declare it on the prototype object.

So you can do something like

 newObj.prototype.add = function(n) { return this.x+n } 

And then do not declare add on the object as before.

In V8, there is a thing called hidden classes , which basically means that all instances of newObj will share the hidden class until you "Make changes to the instance, which (as I understand it) will effectively make all newObj share the method, as with prototyping.

+1
source share

All Articles