simplesthing
simplesthing

Reputation: 3394

Does it affect Angular performance to have everything in scope?

I was wondering if anyone has advice for the usage of $scope vs plain JavaScript objects when inside a module. For instance I have some variables in a controller that I am attaching to $scope for my convenience but they could just be a regular object inside the controller without any functional difference.

My question is does it affect performance when Angular enters a digest cycle to have everything in scope?

Is this :

$scope.viewpanel = {};
$scope.viewpanel.date = new Date();
$scope.viewpanel.day = $scope.viewpanel.date.format('d');
$scope.viewpanel.week = $scope.viewpanel.date.format('W');
$scope.viewpanel.month = $scope.viewpanel.date.format('m');
$scope.viewpanel.year = $scope.viewpanel.date.format('o');

better or worse than this :

var viewpanel ={};
viewpanel.date = new Date();
viewpanel.day = viewpanel.date.format('d');
viewpanel.week = viewpanel.date.format('W');
viewpanel.month = viewpanel.date.format('m');
viewpanel.year = viewpanel.date.format('o');

Upvotes: 2

Views: 568

Answers (1)

Jonathan Rowny
Jonathan Rowny

Reputation: 7588

Yes, it does affect performance if you are using it in your template, which creates watchers automatically. If they aren't bound to anything, then it doesn't matter that much (there is some overhead added), but lots of people don't like crowded scopes. This wiki article on Scopes will explain exactly what happens when you add something to $scope.

Another alternative is bind-once or angular-once. It's like regular binding but only sets it one time so it reduces the number of watchers.

Also, for your specific example, you may consider using filters to format dates. Although that won't help with performance per se, it'll give you cleaner code.

Upvotes: 3

Related Questions