4

I've started using trackBy for some of the ngFor iterations in my app to improve performance.

When debugging I noticed the the trackBy function is called multiple times. I was in the expectation that the trackBy function would be called 1 x n times, where n is the number of items in the array.

I have a simple unordered list in the template

<ul>
  <li *ngFor="let item of items; trackBy: trackByFn">{{item.name}}</li>
</ul>

And I return the id of the item in the trackBy function

trackByFn(index, item): void {
    return item.id;
}

In this StackBlitz the trackBy function is called 2 x n on init. https://stackblitz.com/edit/angular-tm6zdh In my app it is even called 7 x n times.

Is it normal the function is called multiple times?

Should I be worried about performance when the function is called multiple times?

Also, when is the trackBy function actually triggered by Angular? I'm asking, because in my app the trackBy function is also triggered when scrolling through the page, which does not update any of the items in the list. I can't reproduce it in a Stackblitz

emery
  • 137
  • 2
  • 8
  • This should be reopended - Its a very good question and very different to calling a function directly within the HTML template - I appreciate that the best solution may be similar or possibly even identical, but just because the solution is the same does not make the question the same ... e.g. Q: which band sounds like royalty A: queen Q: who is the UK monarch A: queen ... very different questions with the same answer - this is not a dupe – danday74 Jul 31 '21 at 01:42

1 Answers1

2

It's Angular's standard change detection running. Adding changeDetection: ChangeDetectionStrategy.OnPush to the component's declaration should decrease the number of trackBy function calls.

mbojko
  • 13,503
  • 1
  • 16
  • 26