2

In this example:

function foo () {
  function bar () {
    return 'foo bar';
  }
  bar();
}
foo();

Is bar reevaluated for every x times that foo is called?

Conversely:

function bar () {
  return 'foo bar';
}
function foo () {
  bar();
}
foo();

This benchmark shows that the later example is +/- 1.6x faster (in Chrome).

If not reevaluated, why would the 2nd pattern be significantly faster than the 1st pattern?

jtrumbull
  • 818
  • 9
  • 19
  • 2
    The complete function body is evaluated every time you run it. As soon as `bar` function declaration is a part of the body - it is also evaluated every time. – zerkms Feb 28 '16 at 21:57
  • Thanks. I half knew the answer to my question before asking it -simply from practical experience. I guess my "between-the-lines" question, is how would I go about verifying this? Does it change from browser to browser? The standard "How does JavaScript work?" google search didn't produce helpful results. – jtrumbull Feb 28 '16 at 22:13
  • functions are allowed to be cached internally, so `bar()` might not be 100% re-created each time (the function body in particular can be cached since it's static) but it will have to have it's envelope re-built, while the 2nd one needs no such setup costs. – dandavis Feb 28 '16 at 23:38

1 Answers1

1

Short answer: Yes.

As is mentioned in the comments for your question, everything in the function body is run whenever you call the function.

The second example is faster because it only has to call a previously initialised function, whereas in your first example, the code has to re-initialise the function every time. Basically, it's having to repeat the work each time foo() is called, which takes up extra processing time.

millerbr
  • 2,951
  • 1
  • 14
  • 25