Sean_A91
Sean_A91

Reputation: 353

Are nested functions recreated each call?

I was curious about how this was usually handled, I assume it mainly depends on the engine's implementation, but for the sake of example, lets use chrome, are nested functions recreated each time I call the outer function, or are they simply stored somewhere and only made accessible within that scope?

Upvotes: 2

Views: 610

Answers (2)

GOTO 0
GOTO 0

Reputation: 47672

A copy of an inner function is produced each time the outer function is called. This isn't a matter of browser optimization, but rather a necessity, since each closure needs to keep references to variables declared in its own outer scope.

function outer()
{
  function inner()
  {
  }
  return inner;
}

var inner1 = outer();
var inner2 = outer();

console.log('Inner functions are ' + (inner1 === inner2 ? 'identical' : 'different'));

Anyway, this doesn't mean that those instances are not optimized for performance at engine level and cached at runtime. For example Chromium caches both function compilation data and call sites, i.e., a place in code where a function call occurs, to speed up execution.

Upvotes: 1

Barmar
Barmar

Reputation: 780994

The function body will be compiled once and stored somewhere. However, if the function references any free variables, it will have a closure environment in it that changes each time the parent function is called, to capture the variable bindings from that call.

Upvotes: 2

Related Questions