Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$scope vs this performance

Difference between this vs $scope is clearly answered in this question. One of the projects I am working in, Our senior guy is promoting this over $scope arguing it provides better performance.

I tried to find any evidence for the same but official angular documents do have very limited information on this matter.

Can any one please explain

  1. Is this provide better performance over $scope (provided I don't use $watch etc)
  2. If yes for what exact reasons ? is the performance improvement significant enough to change an existing application using $scope to this ?
like image 862
Yogesh Avatar asked Jul 15 '15 05:07

Yogesh


People also ask

What is $scope vs this?

"How does this and $scope work in AngularJS controllers?" When the controller constructor function is called, this is the controller. When a function defined on a $scope object is called, this is the "scope in effect when the function was called". This may (or may not!) be the $scope that the function is defined on.

What is the difference between $scope and scope?

In short, in case of dependency injection the scope object is received as $scope while in case of non-dependency injection scope object is received as scope or with any name. Save this answer.

What is $rootScope in angular?

All applications have a $rootScope which is the scope created on the HTML element that contains the ng-app directive. The rootScope is available in the entire application. If a variable has the same name in both the current scope and in the rootScope, the application uses the one in the current scope.


1 Answers

AngularJS performance is affected by the number of binding the currently loaded view (page) is using and the watches that you setup manually using $watch. All this binding only work on properties declared on $scope.

This means if you are not binding a property to view or not watching it, you better not declare it on the $scope (also called avoiding scope pollution).

Coming to this, as explained in the SO post this has different context when invoked by Angular (such as in case of ng-click) and when controller is created.

So anything that you declare on this (when referring to controller) technically cannot be bound to the view as it is not declared on the scope.

But Angular came up with a controller as syntax where it allow us to use properties and method over the controller object. In such scenario properties declared over controller are bound in the view using ctrl.prop syntax. Internally Angular does something like this when you do ng-controller='HomeController as ctrl'

$scope.ctrl=this

Which basically means Angular is attaching the complete controller object to the $scope and hence binding with controller properties work.

So only thing that matter in terms of performance is the number of binding being watched.

like image 149
Chandermani Avatar answered Oct 13 '22 11:10

Chandermani