Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 830
Raynos Avatar asked Mar 24 '11 14:03

Raynos


People also ask

What is function caching?

How does Caching work? The data in a cache is generally stored in fast access hardware such as RAM (Random-access memory) and may also be used in correlation with a software component. A cache's primary purpose is to increase data retrieval performance by reducing the need to access the underlying slower storage layer.

What is a local function in Lua?

When we store a function into a local variable we get a local function, that is, a function that is restricted to a given scope. Such definitions are particularly useful for packages: Because Lua handles each chunk as a function, a chunk may declare local functions, which are visible only inside the chunk.

Are function variables local?

An assignment statement in a function creates a local variable for the variable on the left hand side of the assignment operator. It is called local because this variable only exists inside the function and you cannot use it outside.

What is local () in Python?

Definition and Usage The locals() function returns the local symbol table as a dictionary. A symbol table contains necessary information about the current program.


1 Answers

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.

like image 96
Erik Kaplun Avatar answered Oct 03 '22 21:10

Erik Kaplun