Performance: filter operator for selection
MEDIUM IMPACT
This affects how quickly the UI updates when filtering data streams, impacting interaction responsiveness and rendering speed.
import { Component } from '@angular/core'; import { Subject } from 'rxjs'; import { debounceTime, distinctUntilChanged, filter, map } from 'rxjs/operators'; @Component({ selector: 'app-filter', template: `<input (input)="onInput($event)" aria-label="Filter items" /> <ul><li *ngFor="let item of filteredItems">{{item}}</li></ul>` }) export class FilterComponent { items = ['apple', 'banana', 'cherry', 'date']; filteredItems = this.items; input$ = new Subject<string>(); constructor() { this.input$.pipe( map(value => value.trim()), debounceTime(300), distinctUntilChanged(), filter(value => value.length > 0) ).subscribe(value => { this.filteredItems = this.items.filter(item => item.includes(value)); }); } onInput(event: Event) { const input = (event.target as HTMLInputElement).value; this.input$.next(input); } }
import { Component } from '@angular/core'; import { Subject } from 'rxjs'; @Component({ selector: 'app-filter', template: `<input (input)="onInput($event)" /> <ul><li *ngFor="let item of filteredItems">{{item}}</li></ul>` }) export class FilterComponent { items = ['apple', 'banana', 'cherry', 'date']; filteredItems = this.items; input$ = new Subject<string>(); constructor() { this.input$.subscribe(value => { this.filteredItems = this.items.filter(item => item.includes(value)); }); } onInput(event: Event) { const input = (event.target as HTMLInputElement).value; this.input$.next(input); } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Immediate filter on every keystroke | Multiple updates per input | Multiple reflows per keystroke | High paint cost due to frequent changes | [X] Bad |
| Filter with debounce and distinctUntilChanged | Single update after typing pause | Single reflow per filter | Lower paint cost with fewer updates | [OK] Good |