0
0
Angularframework~8 mins

Observable in component lifecycle in Angular - Performance & Optimization

Choose your learning style9 modes available
Performance: Observable in component lifecycle
MEDIUM IMPACT
This affects interaction responsiveness and memory usage during component lifecycle events.
Subscribing to an Observable in a component without unsubscribing
Angular
subscription = new Subscription();

ngOnInit() {
  this.subscription.add(
    this.dataService.getData().subscribe(data => {
      this.data = data;
    })
  );
}

ngOnDestroy() {
  this.subscription.unsubscribe();
}
Unsubscribing cleans up resources, preventing memory leaks and reducing CPU load.
📈 Performance Gainavoids memory leaks and reduces CPU usage during component destruction
Subscribing to an Observable in a component without unsubscribing
Angular
ngOnInit() {
  this.dataService.getData().subscribe(data => {
    this.data = data;
  });
}
Subscription stays active after component is destroyed, causing memory leaks and unnecessary processing.
📉 Performance Costcauses memory leaks and increases CPU usage over time
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Subscribe without unsubscribeNo direct DOM ops but triggers repeated change detectionMultiple reflows if data updates frequentlyHigh paint cost due to unnecessary updates[X] Bad
Subscribe with unsubscribe on destroyMinimal DOM ops triggered only on relevant data changesSingle or minimal reflowsLower paint cost due to controlled updates[OK] Good
Rendering Pipeline
Observables trigger asynchronous updates that affect the rendering pipeline by causing change detection and re-rendering when new data arrives.
JavaScript Execution
Style Calculation
Layout
Paint
⚠️ BottleneckJavaScript Execution due to excessive or lingering subscriptions causing repeated change detection cycles
Core Web Vital Affected
INP
This affects interaction responsiveness and memory usage during component lifecycle events.
Optimization Tips
1Always unsubscribe from Observables in ngOnDestroy to prevent memory leaks.
2Use Subscription.add() to manage multiple subscriptions easily.
3Avoid long-lived subscriptions that update UI unnecessarily.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance risk of subscribing to an Observable in Angular without unsubscribing?
ASlower initial page load
BMemory leaks and increased CPU usage
CIncreased bundle size
DReduced network speed
DevTools: Performance
How to check: Record a session while interacting with the component, then look for long scripting tasks and frequent change detection cycles.
What to look for: Look for repeated JavaScript execution spikes and excessive layout recalculations indicating lingering subscriptions.