efficiency of anonymous function storage

Suppose I create an object factory like so:

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)
...

Does each obj1,obj2,... store their own copy of obj.add or do they all contain a reference to a single instance of obj.add stored in memory?

Thanks!


Both obj and obj2 will instantiate their own copies of obj.add . They are function expressions that get executed at creation and stored in memory for the duration of the object's lifetime.

If you want to maintain performance, what you should use is 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 space in memory for the exact same function.


They will all have their own instances of that method.

If you use prototypes, they will share that method, given you declare it on the prototype object.

So you could do something like

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

And then not declare add on the object as before.

In V8 there is a thing called hidden classes which basically means that all newObj instances will share a hidden class as long as you don't make changes to an instance, which would (as far as I understand) effectively make all the newObj's share the method as with prototyping.

链接地址: http://www.djcxy.com/p/14576.html

上一篇: C ++延迟任务

下一篇: 匿名功能存储的效率