Pipes help change how data looks in your app. But if they run too much, your app can slow down. Knowing how to keep pipes fast makes your app smooth and happy.
0
0
Pipe performance considerations in Angular
Introduction
When you want to format dates or numbers in your app display.
When you need to filter or sort lists shown to users.
When you want to change text style or case before showing it.
When you want to avoid slowing down your app by running heavy calculations repeatedly.
Syntax
Angular
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'examplePipe', pure: true // or false }) export class ExamplePipe implements PipeTransform { transform(value: any, ...args: any[]): any { // change value here const changedValue = value; // example placeholder return changedValue; } }
Pure pipes run only when input changes, so they are faster.
Impure pipes run every time change detection runs, which can slow your app.
Examples
This pure pipe changes text to uppercase only when the input text changes.
Angular
@Pipe({ name: 'purePipe', pure: true })
export class PurePipe implements PipeTransform {
transform(value: string): string {
return value.toUpperCase();
}
}This impure pipe sorts an array but runs on every change detection, which can slow the app if the array is large.
Angular
@Pipe({ name: 'impurePipe', pure: false })
export class ImpurePipe implements PipeTransform {
transform(value: number[]): number[] {
return value.slice().sort();
}
}Sample Program
This example shows a pure pipe that doubles a number. The pipe runs only when the number changes. Clicking the button increases the number and triggers the pipe again.
Angular
import { Component, Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'double', pure: true }) export class DoublePipe implements PipeTransform { transform(value: number): number { console.log('DoublePipe transform called'); return value * 2; } } @Component({ selector: 'app-root', template: ` <h1>Number doubled: {{ number | double }}</h1> <button (click)="increment()">Increment</button> ` }) export class AppComponent { number = 1; increment() { this.number++; } }
OutputSuccess
Important Notes
Use pure pipes for simple, fast transformations to avoid unnecessary work.
Avoid heavy calculations inside pipes; do them outside if possible.
Impure pipes can cause performance issues because they run very often.
Summary
Pipes change how data looks but can slow your app if used carelessly.
Pure pipes run only when inputs change, making them faster.
Impure pipes run every time Angular checks for changes, so use them sparingly.