Question

I am working on angularJs and working on javascript optimization. I recently saw a video by YUI creator who is a javascript expert about javascript optimization. He explained about variable declaration and scopes and how javascript work. and How javascript engine has to look for variable from current scope till global scope to find it etc etc (Ref: http://jonraasch.com/blog/10-javascript-performance-boosting-tips-from-nicholas-zakas)

My question regarding is (not specific to angularjs) is:

when in my controller i declare a function like:

app.controller('Ctrl', function() {
  var func1 = function() {
    console.log("Hello");
  }
  this.func2 = function() {
    console.log("World");
  }

  func1();
  this.func2();
});

Which function should be faster ? I know its a overkill but I am interested in knowing how javascript engine works.

Was it helpful?

Solution

in terms of scope these two are identical (they are both local, not global). the difference is in functionality: the "this.func2" function is "public" (you could call that function with a reference to an instance of the Ctrl object), where as the "var func1" is a "private" function.

in terms of the speed of executing a call, I have put together this small test on jspref: http://jsperf.com/private-vs-public-speed-js

  Benchmark.prototype.setup = function() {
    var obj = (function() {
      this.f1 = function() {
        console.log('a');
      }
      var f2 = function() {
        console.log('a')
      }
      return {
        f1: f1,
        f2: f2
      }
    })();
  };

comparing between "use public method" obj.f1(); to "use private method" obj.f2(); does not seem to show a significant difference most of the time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top