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