qw3n
qw3n

Reputation: 6334

Using an self-calling anonymous function versus using a normal function

I have a variable that is being set based on if it an object has a length as one of its properties. If not then I need to check if one of the properties exists. If so then get the first array stored in that object and return the length, else the variable is set to one. This could be combined all in statement like this.

var b=someObject;
var len = b.num||(b.arrs?(function(a){for(var x in a)return a[x].length})(b.arrs):false)||1;

The other way of doing this is pulling out the function and doing it like this

function getLength(a){for(var x in a)return a[x].length})
var b=someObject;
var len = b.num||(b.arrs?getLength(b.arrs):false)||1;

I was wondering if there is a performance penalty for doing it one way compared to the other? Is there a difference in how the javascript engine looks at them? The reason I would prefer the first way is it keeps me from having a bunch of extra helper functions.

Upvotes: 0

Views: 90

Answers (1)

techfoobar
techfoobar

Reputation: 66663

The anonymous inline version is executed and discarded. Whereas the separate function instance is

a) Kept in memory and popped out with the rest of the local variables, if it is declared within a function

b) Kept in memory for the life time of the page if it is defined in global space as a member of the window object.

So if you are unlikely to need it again, it is best to go the anonymous inline route i believe.

Upvotes: 1

Related Questions