0
0
Angularframework~8 mins

Creating observables in Angular - Performance Optimization Steps

Choose your learning style9 modes available
Performance: Creating observables
MEDIUM IMPACT
This affects how quickly data streams start emitting and how efficiently Angular handles asynchronous data updates.
Creating an observable to emit data updates
Angular
const obs = new Observable(observer => {
  const intervalId = setInterval(() => {
    observer.next(Math.random());
  }, 1000);
  return () => clearInterval(intervalId);
});
Clears the timer when there are no subscribers, freeing resources and avoiding unnecessary work.
📈 Performance GainStops background work when unused, reducing CPU and memory usage.
Creating an observable to emit data updates
Angular
const obs = new Observable(observer => {
  setInterval(() => {
    observer.next(Math.random());
  }, 1000);
});
This observable never completes and lacks cleanup logic for the timer, causing it to continue running even after unsubscription, wasting resources.
📉 Performance CostKeeps timer running indefinitely, causing unnecessary CPU usage and memory retention.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Observable with no cleanup000[X] Bad
Observable with cleanup on unsubscribe000[OK] Good
Rendering Pipeline
Creating observables impacts the JavaScript execution and event handling stages, influencing how quickly data updates propagate to the UI.
JavaScript Execution
Event Handling
Rendering
⚠️ BottleneckJavaScript Execution due to continuous timers or heavy synchronous work inside observables.
Core Web Vital Affected
INP
This affects how quickly data streams start emitting and how efficiently Angular handles asynchronous data updates.
Optimization Tips
1Always add cleanup logic to observables to stop background work on unsubscribe.
2Avoid creating observables that run continuous timers without subscriber control.
3Efficient observables improve input responsiveness and reduce CPU usage.
Performance Quiz - 3 Questions
Test your performance knowledge
What is a key performance risk when creating observables without cleanup?
AThe observable emits values too slowly
BUnnecessary background tasks continue running
CThe observable completes immediately
DThe observable blocks the UI thread
DevTools: Performance
How to check: Record a performance profile while subscribing and unsubscribing to the observable. Look for continuous timer callbacks or long-running tasks.
What to look for: Check if timers or callbacks continue running after unsubscription, indicating resource leaks.