Javascript noob question – which one of the following is best practice and performance friendly, also welcome any other suggestions too. This is simplest version of original project. There will be 20+ variables and 10+ inner functions (Ex: ‘process’ in the case).
The advantage of Method 1 is it doesn’t need to send arguments to the functions but as it nests all the functions inside the main function (possibly regenerate all the inner function for each instance of Foo). While the method 2 is free from function nesting but requires lot of arguments. Note that also there will be multiple instance of Foo constructor.
Method 1:
function Foo () {
var a = 1;
var b = 2;
var c = (a+b)/2;
var $element = $('#myElement');
var process = function (){
var x = a+b+c;
$element.css('left', x)
return x;
}
x = process ();
}
Method 2:
function Foo () {
var a = 1;
var b = 2;
var c = (a+b)/2;
var $element = $('#myElement');
x = process (a, b, c, $element);
}
function process (a, b, c, $element){
$element.css('left', x)
return x;
}
The separated functions are definitely the way to go for performance. While there are situations where the variable scoping of nested functions would be nice to have, the performance hit can be huge if the function is large.
Keep in mind that every time Foo if called, var process is reallocating all the memory for the new function that is being created, rather than keeping the function in memory and just passing it new parameters. If the function is big, this is going to be a pretty intense task for the Javascript interpreter.
Here are some hard numbers that may help as well (Contains performance comparisons and actual benchmarks that you can run in your own browser): http://jsperf.com/nested-functions-speed, http://jsperf.com/nested-named-functions/5