Performance: Creating custom pipes
Custom pipes affect rendering speed by how often they run during change detection and how complex their logic is.
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'goodPipe', pure: true }) export class GoodPipe implements PipeTransform { transform(value: any): any { // simple or memoized logic return fastCalculation(value); } } // Usage in template: {{ data | goodPipe }}
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'badPipe', pure: false }) export class BadPipe implements PipeTransform { transform(value: any): any { // complex logic return heavyCalculation(value); } } // Usage in template: {{ data | badPipe }}
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Impure pipe with heavy logic | No extra DOM nodes | Multiple recalculations cause layout thrashing if UI updates | High CPU paint blocking | [X] Bad |
| Pure pipe with simple logic | No extra DOM nodes | Minimal recalculations only on input change | Low CPU paint blocking | [OK] Good |
{{ 'hello' | exclaim }} if the pipe is defined as:import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'exclaim' })
export class ExclaimPipe implements PipeTransform {
transform(value: string): string {
return value + '!';
}
}import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'reverse' })
export class ReversePipe {
transform(value: string): string {
return value.split('').reverse().join('');
}
}Pass the test and this pattern moves unknown