Search code examples
javascriptperformancefunctionoptimizationactivation

Is it better to exit from a Function to cut-down on Activation Objects, than recursively or calling nested functions?


In JavaScript and other languages, I've heard about Activation Objects being created as you invoke a method / function. In order to optimize and maintain a good performance, it sounds like a developer should limit how many functions are being called.

Now if there's no way around it and you must call multiple methods, is it better to call one method after another, like this:

myFunc1();
myFunc2();
myFunc3();

// or...
var myFuncs = [myFunc1, myFunc2, myFunc3];
for(var a=0, aLen=myFuncs.length; a<aLen; a++) {
  myFuncs[a]();
}

OR, to nest them like this:

function myFunc1() {
  // Do something...
  myFunc2();
}

function myFunc2() {
  // Do Something else...
  myFunc3();
}

function myFunc3() {
  //Do one last thing.
}

//Start the execution of all 3 methods:
myFunc1();

I'm assuming it makes more sense to go with the 1st technique, since it comes back to the previous scope and releases the last Activation Object... but if someone could confirm this, I would really like to know!

Thanks


Solution

  • For information concerning Activation Objects, please refer to http://dmitrysoshnikov.com/ecmascript/chapter-2-variable-object/#more-546

    This is not an optimization level concern however, as the concern you listed is an example of EXTREME pre-optimization and your time is not worth that type of investment. And actually, the example you listed above, there is little to no savings when you are looking at Activation Objects alone.

    As for proper use however, I try to encapsulate as much as I can. If a function doesn't have to go in the global scope, and can live within the scope of another function, then that's where it should be declared.

    for example, for better scoping.

    
    var f2 = function() {
    }
    
    var f1 = function() {
      f2()
    }
    
    // is not as nice as:
    
    var f1 = function() {
      var f2 = function()
    
      f2()
    }
    
    // or even better.. 
    
    var f1 = function() {
      function() {
      }()  ; execute
    }