Performance: Pure vs impure pipes
This concept affects how often Angular recalculates and updates the displayed data, impacting rendering speed and responsiveness.
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'pureExample', pure: true }) export class PureExamplePipe implements PipeTransform { transform(value: any): any { // same calculation return value.map(item => item * 2); } }
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'impureExample', pure: false }) export class ImpureExamplePipe implements PipeTransform { transform(value: any): any { // expensive calculation return value.map(item => item * 2); } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Pure Pipe | Minimal - only on input change | Few - only when data changes | Low - fewer repaints | [OK] Good |
| Impure Pipe | Repeated on every change detection | Many - triggers frequent reflows | High - frequent repaints | [X] Bad |
items = [1, 2, 3];
// Template: {{ items | customPipe }}customPipe is pure and the array items is mutated by items.push(4) without changing the reference, what will happen?@Pipe({ name: 'filterPipe', pure: true }). It filters an array based on user input. The filtered results do not update when the user types. What is the likely cause?Pass the test and this pattern moves unknown