Here are two samples of js code:
A. function _foo is defined within the global context
function _foo(){ //some code here
}
//... some unrelated code here
var foo = function(){
var result = _foo();
return result;
}
B. function _foo is defined within the function context
var foo = function(){
function _foo(){ //some code here
}
var result = _foo();
return result;
};
Which one of them is a better programming practice in terms of memory management? Since the function foo will be called many times in the application, is it better to keep _foo in the global context (of the app) and not create it within the function context everytime foo is called? Or since _foo will be (mostly) used inside foo, it makes sense to keep it part of the activation object?
C: Caching
Foo is immediately executed and the function
_foois only declared once.In modern browsers this is 5% slower then a “global” function.
Relevant Benchmark