0

If I am not worried about polluting the global scope and the only place where function b() is getting called from is function a(), which of the following is in terms of performance a better solution?

var v;
function a()
{
    function b()
    {
        v*=v;
    }
    v=5;
    b();
}
a();

or

var v;
function a()
{
    v=5;
    b();
}
function b()
{
    v*=v;
}
a();
pishpish
  • 2,574
  • 15
  • 22

2 Answers2

2

When you use a symbol, its associated value is looked for in the chain of environments, starting from the inner one and moving outwards. This means that the inner (local) environment is found first than the global one but there is no real difference in performance.

To choose which solution to adopt just ask yourself:

  • the inner function could be useful to some other function in the future?

and if not,

  • can I abstract the inner function in a way that creates a more general function that could be useful elsewhere?
  • and what if _var v_ wasn't global, but was passed on to the inner function? – pishpish Jun 17 '13 at 13:09
  • If `v` is passed to the inner function as an argument you are shifting from a side-effect approach to a functional approach, that is almost always better. You are achieving the same result not manipulating a global variable but manipulating your function arguments. From the point of view of performance there is still no difference. The formal parameter `v` would be in the innermost environment (the local environment of the inner function). It would be found first than the outer and global environments. But again, this does not affect performance, important things are others.. – Domenico De Felice Jun 19 '13 at 21:31
1

Looking at my question three years later, I wish to provide a more satisfactory answer.

If the inner function will be used elsewhere, don't nest it. For obvious reasons.

function a(){
  // ...
}
function b(){
  // ...
  a();
}

a();
b();

If the inner function will not be used elsewhere, nest it. It looks cleaner, and increases the outer function's logical integrity (relevant stuff is visually enclosed).

function b(){
  function a(){
    // ...
  }

  // ...
  a();
}

b();

If the inner function will not be used elsewhere and the outer function will be called more than once, make a closure out of it and define the inner in the enclosed scope. This way it won't be redefined on each call. This makes more sense when the inner function is complicated and/or the outer function is called many times.

var b = (function b(){
  function a(){
    // ...
  }

  return function(){
    // ...
    a();
  };
}());

b();
b();

Other performance impacts are negligible.

pishpish
  • 2,574
  • 15
  • 22