user1106995
user1106995

Reputation: 800

Javascript - Arguments Vs Nested functions Vs Performance

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;
}

Upvotes: 5

Views: 1696

Answers (2)

Thorsten Lorenz
Thorsten Lorenz

Reputation: 11847

Actually browsers do optimize even nested functions to where performance differences compared to functions declared in outer scope become negligible.

I blogged my findings and created a performance test to support this claim.

EDIT: The test was broken, after fixing the test shows that it's still faster not to nest functions.

Upvotes: 2

Andrew Odri
Andrew Odri

Reputation: 9432

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

Upvotes: 4

Related Questions