Search code examples
javascriptperformancenested-function

Nesting functions and performance in javascript?


Some of coworkers are saying that nesting functions is bad for performance and I wanted to ask about this.

Lets say I have the function:

function calculateStuff() {
    function helper() {
    // helper does things
    }
    // calculateStuff does things
    helper();
}

helper is a private function that is only used inside calculateStuff. That's why I wanted to encapsulate this inside calculateStuff.

Is this worse performance wise than doing:

function helper() {

}

function calculateStuff() {
    helper();
}

Notice that in the second case, I expose helper to my scope.


Solution

  • With your first code, at each call of calculateStuff, a new copy of helper will be created.

    With your second code, all calls will share the same helper, but it will pollute the outer scope.

    If you want to reuse helper without polluting the outer scope, you can use an IIFE:

    var calculateStuff = (function () {
      function helper() {
        // helper does things
      }
      return function() {
        // calculateStuff does things
        helper();
      }
    })();