Performance: Unsubscribing and memory leaks
HIGH IMPACT
This concept affects the page's memory usage and responsiveness by preventing unnecessary background tasks and DOM updates.
import { Component, OnInit, OnDestroy } from '@angular/core'; import { interval, Subscription } from 'rxjs'; @Component({ selector: 'app-good', template: '<p>Good example</p>' }) export class GoodComponent implements OnInit, OnDestroy { private sub?: Subscription; ngOnInit() { this.sub = interval(1000).subscribe(val => console.log(val)); } ngOnDestroy() { this.sub?.unsubscribe(); } }
import { Component, OnInit } from '@angular/core'; import { interval } from 'rxjs'; @Component({ selector: 'app-bad', template: '<p>Bad example</p>' }) export class BadComponent implements OnInit { ngOnInit() { interval(1000).subscribe(val => console.log(val)); } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No unsubscribe | N/A (keeps event listeners active) | Triggers multiple reflows indirectly via change detection | Increased paint cost due to unnecessary updates | [X] Bad |
| Unsubscribe on destroy | No extra DOM operations after destroy | No reflows triggered after unsubscribe | Minimal paint cost after unsubscribe | [OK] Good |