Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using var foo = function foo() {}; expression creating a memory leak in IE < 9?

I know that this form:

var foo = function bar() {};

will leak the bar name to the enclosing scope and create two functions in jscript.

How about:

var foo = function foo() {};

?

It still leaks the name to enclosing scope, but it's in there anyway (thx to var foo).

I know it will be defined in the whole scope, but will it create two functions and immediately dereference/destroy one of them or is this still causing a leak?

In this situation:

var bar = function() {
    foo();
    var foo = function foo() {};
}

Will we have two function objects inside bar()?

edit

Ok it most definitely creates two function objects, now the question is: does the function created by named definition get dereferenced and cleaned up by GC after the var foo line, so there is no more than one 'live' foo instance at any moment in the code above?

Or will IE being IE leave it dangling forever, since there's no way to "dereference" the foo created by the definition and it shouldn't even be there in the first place?

like image 312
soulcheck Avatar asked May 30 '13 11:05

soulcheck


People also ask

What can cause memory leak in Javascript?

The main cause of memory leaks in an application is due to unwanted references. The garbage collector finds the memory that is no longer in use by the program and releases it back to the operating system for further allocation.


1 Answers

When parsing the statement var foo = function foo() {};, the var foo declaration is most likely assigned after function foo(){} is executed.

That means that function foo will be defined in the global scope, that is usual window, first.

After that, var foo becomes assigned and thus hiding window.foo from your scope for the name foo. So in fact, your code defines window.foo or window.bar, which is not garbage collected if your current scope is left.

like image 51
dronus Avatar answered Oct 11 '22 18:10

dronus