spender
spender

Reputation: 120400

Anonymous functions and memory consumption

In terms of memory consumption, are these equivalent or do we get a new function instance for every object in the latter?

var f=function(){alert(this.animal);}
var items=[];
for(var i=0;i<10;++i)
{
    var item={"animal":"monkey"};
    item.alertAnimal=f;
    items.push(item);
}

and

var items=[];
for(var i=0;i<10;++i)
{
    var item={"animal":"monkey"};
    item.alertAnimal=function(){alert(this.animal);};
    items.push(item);
}

EDIT

I'm thinking that in order for closure to work correctly, the second instance would indeed create a new function each pass. Is this correct?

Upvotes: 5

Views: 280

Answers (2)

jwueller
jwueller

Reputation: 30996

You should pefer the first method, since the second one creates a function every time the interpreter passes that line.

Regarding your edit: We are in the same scope all the time, since JavaScript has function scope instead of block scope, so this might be optimizable, but i did not encounter an implementation that doesn't create it every time. I would recommend not to rely on this (probably possible) optimization, since implementations that lack support could likely exceed memory limits if you use this technique extensively (which is bad, since you do not know what implementation will run it, right?).

Upvotes: 5

micho
micho

Reputation: 2226

I am not an expert, but it seems to me that different javascript engines could be handling this in different ways.

For example, V8 has something called hidden classes, which could affect memory consumption when accessing the same property. Maybe somebody can confirm or deny this.

Upvotes: 2

Related Questions