5

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

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, separated functions has better performance even with higher number of arguments. Thanks for the answer.
2

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.

1 Comment

Hmm... they are slightly worse, but I consider this a weak point of the browsers. It so much nicer to write nested code! I love it! I wish all languages supported this, and optimized for this when non-local variables are used.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.