Are local function declarations cached?
function A() {
function B() {
...
}
B();
}
Is function B
created every time A
is called or is there some caching on it. Is not making it local like :
function A() {
B();
}
function B() {
...
}
A significant performance improvement?
Is it valid to do this a style choice? (B
in开发者_C百科 this case is just a helper function for A
.) or should the second be favoured for speed?
Should this style be used or avoided for readability?
Benchmark.
Seems like FF4 inlines B
for the local case and removes the function call overhead.
What about other browsers?
Declaring an inner function in JS might have the purpose of being lexically bound to the outer function's local variables/arguments. Moving it out to be a top-level function defeats that purpose.
To answer the question: yes, the inner function is created every time, at least in theory, and this is how you should view it when writing the code, but a smart optimizer can still convert it to a top-level function, even if you have lexical dependencies. If it's a micro-optimisation, I wouldn't bother because having an inner function also serves the purpose of readability and declaring your intentions.
Raynos, I looked at your jsperf tests, and it looks like you are testing the function declaration, not the function execution.
See the link below. Is that helpful?
Another benchmark
I would say that:
In your sample code, B is created every time A is invoked. (In my sample linked to above, see the Outer Ordinary test.)
Percentage-wise, the performance improvement is significant. But, if the real-world function runs in microseconds, you might not notice a difference.
Another consideration is how important is it for B (the helper function) to be "private" (in other words, visible only inside of A). See the Outer Immediate function in my link for a middle-of-the-road option.
That's odd, because I would guess that re-declaring a function every time another is called would slow down execution time.
Does anyone have an answer to this?
The only solution I can come up with is that function C has to leave it's scope, move up to the global one, execute function D, then go back. Whereas function A stays within one scope through out execution. Any thoughts?
精彩评论