0

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?

FreddyNoNose
  • 478
  • 1
  • 7
  • 13

2 Answers2

1

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.

rousan
  • 301
  • 4
  • 9
  • I should have put more code here. This is an object pool. Suppose pool[100] was not needed anymore and we want to reuse it. So the var obj = pool[100];...; constructor.apply(obj, arguments); Then we put obj back into pool[100]. The questions that need to be answered are: 1) new vs apply, are we going to reuse memory or are we still creating the same thing as new. If so, then object pool is a useless idea because it doesn't prevent GC during apply. I don't you answered my questions. My bad perhaps, but it seems reinterpreted question. – FreddyNoNose Jul 16 '17 at 00:43
  • 1
    If you use `apply` then the same object is used every time, but whenever u use `new` then a new object will be created. In this case, if u put back the obj to pool then u are reusing memory and but if u have zero references of the pool then the pool will be garbage collected. – rousan Jul 16 '17 at 08:13
  • Thanks. I had thought that too, but a friend of mine the day before I posted had convinced me I was wrong. Guess I lost confidence in what I believed. – FreddyNoNose Jul 24 '17 at 22:14
0

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375