Reputation: 548
Suppose we have a pool of objects (aka an array). Then we Constructor.apply(obj, arguments).
var obj = objectPool[nextAvailableIndex];
obj.index = nextAvailableIndex;
nextAvailableIndex += 1;
Constructor.apply(obj, arguments);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
What does this do to the existing Obj? Is the memory reused? Does this help avoid GC? Isn't it essentially the same as new or is it similar but different?
Upvotes: 0
Views: 80
Reputation: 665130
What does this do to the existing Obj?
It calls the Constructor
on it, with its this
value set to the obj
. What Constructor
does exactly we do not know, but in general it is supposed to initialise a fresh instance.
Is the memory reused?
Depends in part on what Constructor
does, and how it deals with non-fresh instances. But yes, obj
was never released as it stayed in the objectPool
array, and in contrast to new Constructor(…)
no new object that inherits from Constructor.prototype
is instantiated.
Upvotes: 0
Reputation: 381
Suppose we consider a code snippet like this:
function Constructor() {
this.prop = "some_value";
}
var objectPool = [{}, {}, {}];
var nextAvailableIndex = 0;
function Caller() {
var obj = objectPool[nextAvailableIndex];
obj.index = nextAvailableIndex;
nextAvailableIndex += 1;
Constructor.apply(obj, arguments)
}
In this case when the Caller is called then everytime a new local variable is created named 'obj', but after executing the Caller, that variable is freed.
That's it.
Upvotes: 1