PadaKatel
PadaKatel

Reputation: 307

Angular 2 performance and changeDetection (1000 calls in 5 seconds)

So basically, I am quite new to angular 2 and I took over a project for it.

I found the performance of the app to be quite slow, it is very problematic.

I couldn't find out what caused the slow performance. Then I started noticing that a lot of ngIf's and ngFor's call functions. When I suddenly started to log from these functions I found out that there are literally hundreds of calls in every second.

I really don't have anything interesting to show code-wise, but I was wondering if this is supposed to be normal?

I don't really see anything wrong with the actual code. Of course the results for ngFor can be saved to a variable, but it's a bit more difficult (and kind of useless?) to do the same for ngIf's. I read about changeDetection, but I couldn't determine how often it should actually fire.

Even without changing anything on the website (just scrolling), there are so many calls to the functions.

Upvotes: 1

Views: 1602

Answers (2)

rgantla
rgantla

Reputation: 1956

Yes, some times change detection runs 1000's of times especially when the number of DOM elements getting manipulated is high.

For example: a change in an *ngFor loop over an array would tear down the entire DOM and reconstruct it for the list part. Here change detection needs to run every single time.

While this is true, there are steps you can follow to avoid performance hits.

1) using trackBy on your *ngFor loops: this significantly improves the performance since angular tries to make changes to only the changed/new part of the array rather than tearing down and reconstructing the entire array again.

you can see it in action here: angular docs

2) Don't use functions inside string interpolation as demonstrated below:

<div>the selected color is: {{selectedColor()}}</div>

Hope this helps.

Upvotes: 2

monogate
monogate

Reputation: 1439

I was wondering if this is supposed to be normal?

The answer is yes.

You bind a function to your ngIf. Angular needs to track your function and render as fast as possible the conditioned element.

If you have an ngIf with many instructions, then you are doing something wrong.

Keep your conditions slim as possible so the ChangeDetection performance will not hurt the user experience.

Upvotes: 2

Related Questions