what is the lifetime of javascript anonymous function?

  • A+

If I write this in global scope:


is the anonymous function created when the statement is executed and destroyed immediately after the statement is executed?

if I write this in a function:

function foo() {     var a=1;     (function(){})();     a++; } 

Does the anonymous function exist until foo returns, or just exist during the execution of that statement?


In this particular case, most engines will optimize that function entirely away, because it does not do anything.

But let's assume that function contains code and is indeed executed. In this case, the function will exist all the time, either as compiled code, as bytecode or as AST for the interpreter.

The part that won't exist all the time is the scope and the possible created closure. The scope created for that function and the closure will only exist as long as the function is executed or a reference to the function with a specific bound scope/closure exists.

So the combination function reference + scope will be allocated at the time the statement (function(){})(); is executed, and can be released after that statement. But the compiled version of function(){} might still exist in memory for later use.

For engines that do just in time compiling and optimization, a function might even exist in different compiled versions.

The JIT+optimizer part of modern js engines is a complex topic, a rough description of v8 can be found here html5rocks: JavaScript Compilation:

In V8, the Full compiler runs on all code, and starts executing code as soon as possible, quickly generating good but not great code. This compiler assumes almost nothing about types at compilation time - it expects that types of variables can and will change at runtime.

In parallel with the full compiler, V8 re-compiles "hot" functions (that is, functions that are run many times) with an optimizing compiler. [...] In the optimizing compiler, operations get speculatively inlined (directly placed where they are called). This speeds execution (at the cost of memory footprint), but also enables other optimizations.

Therefore it may be that the generated code has hardly any similarities to the original one.

So a immediately-invoked function expression might even be completely optimized away using inlining.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: