Are local function declarations recorded?

function A() { function B() { ... } B(); } 

Is function B every time A is called or is there caching on it. Does not make it local, like:

 function A() { B(); } function B() { ... } 

Significant performance improvement?

Is this really a style choice? ( B in this case is only an auxiliary function for A ), or if the second is needed for speed?

Should this style be used or avoided for readability?

Benchmark

It seems that FF4 inlines B for the local case and removes the function call overhead.

What about other browsers?

+7
source share
3 answers

Declaring an internal function in JS may be due to lexical binding of local variables / arguments to the external variable. Moving it for a top-level function hits this target.

To answer the question: yes, an internal function is created every time, at least theoretically, and that is how you should look at it when writing code, but the intelligent optimizer can convert it to a top-level function, even if you have lexical dependencies. If it’s micro-optimization, I wouldn’t worry, because the internal function also serves to read and announce your intentions.

+4
source

Raynos, I looked at your jsperf tests and it looks like you are testing a function declaration, not a function execution.

See the link below. This is useful?

One more test

I would say that:

  • In your code example, B is generated each time A. is called. (In my example related to above, see External Conventional Testing.)

  • In percentage terms, a significant improvement in performance. But if the real-world function works in microseconds, you may not notice the difference.

  • Another consideration is how important it is for B (the helper function) to be "private" (in other words, visible only inside A). See Outer Immediate Function in my link for the mid-road option.

0
source

This is strange because I assume that re-declaring a function each time another is called will slow down the execution time.

Does anyone have an answer to this question?

The only solution I can come up with is that function C should leave the scope, go global, execute function D, and then return. While function A remains within the same execution area. Any thoughts?

0
source

All Articles