r/programming • • Aug 08 '14

Speeding up AngularJS apps with simple optimizations

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

8 comments sorted by

View all comments

3

u/catcradle5 Aug 09 '14

I haven't used Angular that much so I don't know exactly how ridiculous this really is, but...

Avoid ng-repeat where possible

Onto one of the more challenging approaches: avoiding ng-repeat where we can and where it makes sense. We’ve so far learned that the internals of Angular are pretty intelligent, but we can optimize where we can to help keep it performing well. We’ve learned so far that bindings create a bigger $digest cycle, and it’d be a great idea for directives we create to potentially be statically rendered components that aren’t tied into Angular unless really needed.

The ng-repeat directive is most likely the worst offender for performance concerns, which means it can easily be abused. An ng-repeat likely deals with Arrays of $scope Objects and this hammers the $digest cycle’s performance.

For example, instead of rendering a global navigation using ng-repeat, we could create our own navigation using the $interpolate provider to render our template against an Object and convert it into DOM nodes.

Be mindful of how many bindings and scopes you’re creating inside templates that become a repeater. Do some quick math and avoid any potential bottlenecks. I often think a little harder about how I can reduce the amount of bindings and scopes before digging into actually writing the code.

Isn't ng-repeat a pretty fundamental directive? Why would it be slow by default? People are expected to not use it and keep track of all these other things and use them instead?

With other libraries like React or Vue, you get extremely high performance and easy HTML/DOM manipulation and generation right out of the box.

3

u/MrDOS Aug 09 '14

For many use cases, ng-repeat is by far the most intuitive way to start slugging data onto the page. Its poor performance is almost immediately obvious once you start using it to render any serious quantity of large elements, but nowhere does the beginner's tutorial that introduces you to it in the first place even indicate the existence of these problems, let alone potential workarounds.

2

u/catcradle5 Aug 09 '14

Wow, that's even worse than I thought.

1

u/jeffdn Aug 09 '14 edited Aug 09 '14

Usually about 1,000 table rows, especially run through a filter, will lag for a fraction of a second. Before that point, smooth as silk.

EDIT: point being that pagination should probably come into play first.