Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 715
spender Avatar asked Nov 29 '10 00:11

spender


People also ask

What are anonymous functions good for?

The advantage of an anonymous function is that it does not have to be stored in a separate file. This can greatly simplify programs, as often calculations are very simple and the use of anonymous functions reduces the number of code files necessary for a program.

What is an anonymous function and when should you use it?

Anonymous functions are often arguments being passed to higher-order functions, or used for constructing the result of a higher-order function that needs to return a function. If the function is only used once, or a limited number of times, an anonymous function may be syntactically lighter than using a named function.

What's the most common use case for anonymous functions?

One of the more famous use cases for anonymous functions are Immediately Invokable Function Expressions (IIFE). IIFE, for short, is a pattern that uses an anonymous function which immediately creates and invokes the contents of the function. // IIFE (Immediately Invokable Function Expression) (function() { console.


1 Answers

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

like image 137
jwueller Avatar answered Sep 21 '22 13:09

jwueller