Angular: Is using "trackBy: index" good practice?

Viewed 674

Using "trackBy: index" in ngFor is a good practice or not?

For example :

<li *ngFor="let error of fileErrors.value; trackBy : index;"> {{error}} </li>

Using every time trackBy is necessary in all *ngFor for performance improvement or we can ignore it.

If we ignore then what will be the iterator implementation will be used by default?

1 Answers

Using every time trackBy is necessary in all *ngFor for performance improvement or we can ignore it.

First off, I would like to begin by saying spending time doing micro-optimizations can be a big waste of time and ultimately yield no real result in performance. It is usually best to focus on good coding practices/conventions then at the end of your development cycle circle around to performance when you can properly identify your bottlenecks.

However, when dealing with large collections in Angular it is good practice to use trackBy. If you don't then Angular needs to remove all the DOM elements that are associated with the data and recreate them. That means a lot of DOM manipulations especially in a case of a big collection, and as we know, DOM manipulations are expensive.

Which brings us to your question:

Angular: Is using “trackBy: index” good practice?

The answer is, it depends, it is not necessary in all ngFor directives. Use trackBy appropriately on a case by case basis. If you are dealing with small collections of data then you really won't notice much performance gain and again you will be making premature optimizations which may not yield any notable performance gains.

Edit based off of follow up comment:

What happen if we use in every *ngFor? Even if the collection is not so big?

Using trackBy will result in Angular tracking which items have been added or removed according to the unique identifier and creating or destroying only the things that changed. It is okay to use trackBy in every ngFor if that is what you decide to do. It just isn't necessary and the performance gains will likely be negligible in small collections.

Related