Performance of reference to property or getter from template in Angular

Viewed 3129

I have a question regarding performance in Angular. Is there a performance difference between referencing a public property and a getter defined in a component?

Example:
I have a template, and it references isActivate that is defined in a component like this:

<div *ngIf="isActivate">Do stuff...</div>

In the component:

export class TestComponent {
    public isActivate: boolean;

But it can have a getter instead:

public get isActivate(): boolean {
    return true;
}

In performance wise, which is better, and why?

1 Answers

On each Change detection Angular compare previous and current bound values. Performance difference between getter(i.e. function) vs property access is nothing till function do nothing. If we want to optimize that - memoize the function by using pure pipe.

Another, more general, solution is create apply pipe:

@Pipe({
  name: 'apply',
})
export class ApplyPipe implements PipeTransform {
  transform<T, U extends any[]>(fn: (...fnArgs: U) => T, ...args: U): T {
    return fn(...args);
  }
}

// TS
foo = {};
computeSmth(foo){
  // some computation
  return 'result';
}

// HTML
{{ computeSmth | apply : foo}}

PS also we can use decorator to memoize getter function

Related