Performance: Unsubscribing and memory leaks
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 |
ngOnDestroy method?unsubscribe() method to stop listening.unsubscribe() is valid; others do not exist on Subscription.export class MyComponent implements OnDestroy {
private sub = this.service.getData().subscribe(data => console.log(data));
ngOnDestroy() {
// missing unsubscribe
}
}ngOnDestroy?export class DemoComponent implements OnDestroy {
private subscription: Subscription;
ngOnInit() {
this.subscription = this.service.getData().subscribe();
}
ngOnDestroy() {
this.subscription.unsubscribe;
}
}this.subscription.unsubscribe; without parentheses, so the method is not executed.Pass the test and this pattern moves unknown