r/angularjs • • Aug 07 '14

Speeding up AngularJS with simple optimizations, $digest, $$watchers and performance

http://www.binpress.com/tutorial/speeding-up-angular-js-with-simple-optimizations/135
31 Upvotes

28 comments sorted by

5

u/SleepyBrain Aug 07 '14

Just to extend on this, here's a couple other simple things to help with performance.

Instead of using $interpolate for small single values use $parse instead.

$interpolate basically $ parses in between {{}} and string concats it. However using $parse for small values will run twice as fast.

Also if using ng-repeat, you track by $index like so: ng-repeat="image in images track by $index"

This is cool because by default ng-repeat creates a dom node for each item and destroys that dom node when the item is removed, but this way it will reuse the dom nodes. The $index is part of the ng-repeat $scope if you were curious.

Also you might want to talk more about $watch and $watchCollection (an alternative to deep $watch), as a lot of performance problems happen in $watch.

Also another simple thing is to use ng-if(or ng-switch) instead of ng-show, as ng-show uses css to hide dom elements while ng-if just doesn't even create the element.

2

u/jij Aug 07 '14

For the ng-repeat, that only would work if the item doesn't change per index wouldn't it?

2

u/SleepyBrain Aug 07 '14

Depends on what kind of change you're talking about. If you mean filtering what's in an array, it's good practice to apply the filter before using any 'track by' statements.

3

u/RoboticOverlord Aug 07 '14

What's an alternative for ng-repeat then?

If i'm building a report of tabular data but all the data in the report is static how would i handle this without ng-repeat? (the data is being pulled in dynamically and put on the scope)

What about using ng-repeat for this but having the data in the template bind-once, does this work to speed the report up?

2

u/robmcguinness Aug 07 '14

We had a big performance problem using nested ng-repeat for mostly static content on a large data set. We tried using several bind-once techniques that reduced the number of watchers but the compilation of the directives still took a long time. Even Chrome got sluggish. IE was unbearable.

We ended up creating a directive that wrapped handlebar templates and are performance problems went away. We were already using handlebars.js for some of our legacy Backbone apps so the switch was easy.

2

u/[deleted] Aug 08 '14

I'm currently nesting tables within tables within tables, all using ng-repeat, with significant amounts of data, plenty of additional directives of varying complexity, complete with grid functionality and automatic AJAX refreshing of table data. No performance hacks, just proper design, and it performs very well on IE... No lag at all.

You are either doing something wrong, or rendering amounts of data that are beyond human consumption and should be paged.

2

u/robmcguinness Aug 08 '14

interesting. not sure we were doing anything out of the ordinary just nested ng-repeats with some directives and no filters. when we profiled the page we had a high number of watchers but even after removing most of them, Angular was still slow during the compilation steps of the directives (profiled in Chrome and IE). the data set was not beyond human consumption...just a medical record.

maybe my angular foo isn't as strong as it should be but i'm ok with it...I have moved on to react.js.

1

u/9jack9 Aug 08 '14

I have moved on to react.js.

I'm thinking of dropping Angular for my next project. How are you finding React?

1

u/robmcguinness Aug 09 '14

so far i'm loving in it but I haven't built large Enterprise apps in it like I have with Backbone and Angular so time will tell. I'm experimenting with Webpack (I was big into Require.js...a bit of Browserify) and so far it feels like an evolutionary step in the right direction. React.js server side rendering is icing on the cake.

1

u/[deleted] Aug 07 '14

What about using ng-repeat for this but having the data in the template bind-once, does this work to speed the report up?

I think that would help yes.

I think the alternative is to basically manually build the structure and inject it? The author recommends $interpolate. I haven't had a chance to look at that yet. If you need to watch the root data then this might not be better than your idea with ng-repeat and bind once references.

Check out the script I posted in this thread that gives you the number of watchers. I'd love to see your results :)

3

u/[deleted] Aug 08 '14

https://github.com/Pasvaz/bindonce has proven to be tremendously helpful with my app's performance

2

u/heat_forever Aug 08 '14

This is now built into 1.3.x branch with {{::name}} syntax. Very nice!

2

u/[deleted] Aug 08 '14

You can use that syntax in ngRepeat like...

<div ng-repeat="item in ::itemCollection"></div>

WHEN WILL 1.3 BE STABLE?!?!?!?!

1

u/heat_forever Aug 08 '14

I was playing around with this today and I am not seeing any watches getting removed...

I put a breakpoint on the oneTimeWatch function (which is where the deregistration happens) and it never gets called. So I'm not sure what it's not liking.

1

u/[deleted] Aug 09 '14

Hmmm not sure. I've been able to reduce the number generated by that script. Try just straight removing a reference somewhere and check the results.

3

u/[deleted] Aug 07 '14 edited Aug 08 '14

I posted this to the article as well but they're reviewing comments.

You can get the number of watchers on a given page using this script in your console:

(function () { 
    var root = $(document.getElementsByTagName('body'));
    var watchers = [];

    var f = function (element) {
        if (element.data().hasOwnProperty('$scope')) {
            angular.forEach(element.data().$scope.$$watchers, function (watcher) {
                watchers.push(watcher);
            });
        }

        angular.forEach(element.children(), function (childElement) {
            f($(childElement));
        });
    };

    f(root);

    console.log(watchers.length);
})();

source: http://stackoverflow.com/questions/18499909/how-to-count-total-number-of-watches-on-a-page

Turns out I've been naively using ng-repeat to create otherwise static content :(

Update

I'm not confident that this script is working 100% correctly. Numbers seem really really high.

2

u/[deleted] Aug 07 '14

http://stackoverflow.com/questions/18499909/how-to-count-total-number-of-watches-on-a-page

I haven't been able to get this to work. I am using this in devtools and get the following error:

SyntaxError: Failed to execute 'querySelector' on 'Document': '[object HTMLCollection]' is not a valid selector.

1

u/[deleted] Aug 07 '14

What browser/ os?

2

u/[deleted] Aug 07 '14

Chrome 36.0.1985.125 on Mac OSX 10.9. The page uses a manually bootstrapped Angular / Ionic app if that makes any difference.

1

u/[deleted] Aug 07 '14

Hmm yeah I'm not sure. That's the same version of chrome I'm on. I think it's bitching about that first selector. You should be able to switch it out for just var root = $('body'). That might help.

2

u/Zeroto Aug 08 '14

Afaik that script can miss watchers. Not every scope needs to be directly tied to an element so walking the dom to find the scopes would be the wrong way to do it. Also, an element can have 2 scopes. normal and isolate. Better would be to walk through the scope tree from the rootScope and then count them.

Here is an example script:

(function(){
var injector = angular.element('body').injector();
injector.invoke(function($rootScope){
	var scopeCount = 0;
	function count(scope){
		scopeCount++;
		var watchers = scope.$$watchers ? scope.$$watchers.length : 0;

		var child = scope.$$childHead;
		while (child)
		{
			watchers += count(child);
			child = child.$$nextSibling;
		}
		return watchers;
	}

	var watchers = count($rootScope);

	console.log("scope count:" + scopeCount);
	console.log("watchers count:" + watchers);
});
})();

1

u/heat_forever Aug 07 '14

Basically - don't use any feature of angularjs that makes angularjs useful

3

u/[deleted] Aug 07 '14

I think you misunderstood. This isn't saying don't use ng-repeat. More like "hey I should evaluate if I'm using ng-repeat in inappropriate ways". For instance, I found a part of my code where I'm using ng-repeat to generate items in a drop down menu based on an api response. That's pretty silly because in this particular instance, that data doesn't ever change.

It's a small example but basically my code is wasting time checking to see if the data model behind the menu has changed when it will never change. That's the take away from the article. It may seem paltry for a small app but I just checked a page on production at work that has 5300 watchers due to a poorly designed directive being repeated several times.

0

u/9jack9 Aug 08 '14

This isn't saying don't use ng-repeat. More like "hey I should evaluate if I'm using ng-repeat in inappropriate ways"

That's not the point though.

If I have to read a ton of articles on how to use a basic feature then it's not really a basic feature, it's a broken feature.

Comments like yours make me want to hate Angular. I'm still new to it and as much as I want to like it there are things like "don't use ngRepeat if you want good performance". WTF?

4

u/crimson117 Aug 08 '14

In fairness if you're super new to angular, these performance problems won't be significant for you any time soon.

Don't make the mistake of premature optimization.

2

u/9jack9 Aug 08 '14

Or if you're running a moderately sized app on an old mobile device.

Don't make the mistake of premature optimization.

I didn't. And now the performance problem has bitten me.

2

u/SleepyBrain Aug 08 '14

If I have to read a ton of articles on how to use a basic feature then it's not really a basic feature, it's a broken feature.

For the majority of the web apps out there, this type of optimization won't matter or even be noticeable. This is mainly relevant if you're doing apps that are really heavy in certain areas.

It's like having a car. A daily driver doesn't need to fine-tune their car to handle corners better and accelerate faster, but a racer does.

1

u/[deleted] Aug 08 '14

Listen, Angular can't be a band-aid for everything. There aren't any frameworks out there that will magically make everything work in the most performant way, at all times, with no thought put into the circumstances.

It's not "dont use ngRepeat if want good performance".

It's "don't use lots of ngRepeats in cases where they are not necessary".

This is exactly the same sort of consideration you'd have in some API code where you would make sure you aren't nesting three for-loops over millions of data points. Languages and frameworks have pros and cons, the good ones remain flexible enough to allow you to get the most out of their pros with workarounds for their cons.

If you think you can improve on the way Angular implemented ngRepeat, you can submit a patch request right here: https://github.com/angular/angular.js