DEV Community

Cover image for Angular Speed Improvement Using TrackBy
John Peters
John Peters

Posted on • Updated on

Angular Speed Improvement Using TrackBy

<li 
  *ngFor="let item of items; 
  index as i; 

  trackBy: trackByFn">

</li>
Enter fullscreen mode Exit fullscreen mode

The trackBy directive as shown above is a massive speed enhancer. The reason is that the function it points to, tells Angular the "index" column to use to track changes. Just like databases having unique indexes, if we ensure our tranckByFn returns only unique indexes in our array, Angular will only update those that change!

Paging

Assume an array of People with firstName, lastName, type and address information. Rendering delays are seen with just 2000 records. One way to overcome this; is paging, whereby only a small number of records are retrieved at a time.

Two types of paging designs are

-Paging in the client
-Paging at the server/endpoint

Either work well but each take a bit of thought for proper implementation.

The mat-table has a built in paging control with a built-in paging event. Assuming that we only get our pages based on a maximum response time in sub second ranges, the page event would keep us able to anticipate the next requests. It would work like this.

  • We can only get 200 records at a time to meet the sub second spec.
  • Our paginator page size is set to 10 records per page.
  • We have 20 pages of data for the user ready to go.
  • As each page event fires, we determine when to get additional data.
  • We ensure our trackBy function is configured and working properly.
  • Each new get adds to the existing array, using the unique index formula we described earlier.
  • Angular conserves rendering based on the trackBy, only new items to the array will be rendered, and only when it's needed.

Sound cool? Read this for confirmation

One other consideration: Now that most of us are implementing Async everywhere patterns, we are able to send out multiple Async requests for data which help the equation in that when rendering is needed the data is already there or in a buffer ready to be merged.

JWP2020 Trackby

Top comments (0)