0
0
Angularframework~8 mins

Subscribing to observables in Angular - Performance & Optimization

Choose your learning style9 modes available
Performance: Subscribing to observables
MEDIUM IMPACT
This affects interaction responsiveness and memory usage by controlling how data streams update the UI and how resources are managed.
Managing data streams in Angular components
Angular
private subscription = this.dataService.getData().subscribe(data => {
  this.items = data;
});

ngOnDestroy() {
  this.subscription.unsubscribe();
}
Unsubscribing frees resources and stops unnecessary UI updates after component is destroyed.
📈 Performance Gainprevents memory leaks and reduces INP by stopping unused event listeners
Managing data streams in Angular components
Angular
this.dataService.getData().subscribe(data => {
  this.items = data;
});
No unsubscription leads to memory leaks and continuous UI updates even after component destruction.
📉 Performance Costcauses memory leaks and increases INP due to unnecessary event handling
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Manual subscribe without unsubscribeMultiple updates even after component destroyedMultiple reflows due to repeated change detectionHigh paint cost from unnecessary UI updates[X] Bad
Manual subscribe with unsubscribe in ngOnDestroyUpdates only while component aliveSingle reflow per update cycleModerate paint cost[!] OK
Using async pipe in templateUpdates only when data changes and auto cleans upMinimal reflowsLow paint cost[OK] Good
Rendering Pipeline
Subscribing to observables triggers change detection which leads to style recalculation, layout, and paint. Unmanaged subscriptions cause repeated unnecessary updates.
Change Detection
Style Calculation
Layout
Paint
⚠️ BottleneckChange Detection due to frequent or unnecessary updates
Core Web Vital Affected
INP
This affects interaction responsiveness and memory usage by controlling how data streams update the UI and how resources are managed.
Optimization Tips
1Always unsubscribe from observables to prevent memory leaks.
2Use async pipe in templates to automate subscription management.
3Minimize the frequency of observable emissions to reduce change detection triggers.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance risk of subscribing to observables without unsubscribing in Angular?
AMemory leaks and slower input responsiveness
BFaster page load time
CImproved visual stability
DReduced bundle size
DevTools: Performance
How to check: Record a session while interacting with the component, then look for frequent change detection cycles and long scripting times.
What to look for: Look for repeated change detection events and long scripting tasks indicating unnecessary subscriptions causing slow responsiveness.