Yogesh
Yogesh

Reputation: 4784

$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 ?

Upvotes: 6

Views: 1259

Answers (3)

Chandermani
Chandermani

Reputation: 42669

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.

Upvotes: 5

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

Angularjs uses both of them interchangeably so there's no difference regarding the performance.

But using this should be lower performance (not even so lower) than the $scope as this creates a new instance of the object.

But really using this is more elegant way as:

  • More contextual (for eg. items.name than name)
  • Can be used nested controller easily without any conflicts.

Upvotes: 0

Amir Popovich
Amir Popovich

Reputation: 29836

Assuming you don't have watches it shouldn't create a performance barrier.

In my opinion, you should not have any "this" methods\properties on your controller.
A controller is the view's best friend and should only have relevant properties on it.
A relevant property is a property that you are going to bind inside your view (properties, functions etc.).

All your "this" properties should probably be on a service.

Upvotes: 0

Related Questions