Back to Curriculum

Memory Management and Performance

📚 Lesson 14 of 20 ⏱️ 35 min

Memory Management and Performance

35 min

JavaScript is garbage-collected, meaning the engine automatically frees up memory that is no longer reachable. However, developers can still create **Memory Leaks** by accidentally keeping references to unused objects.

**Common Leak Sources**: Global variables (accidental), Forgotten timers/intervals, Detached DOM elements (removing an element from the DOM but keeping a JS reference to it), and Closures (holding onto large scopes).

**Performance Optimization** involves minimizing reflows/repaints, using `requestAnimationFrame` for animations, debouncing/throttling high-frequency events (scroll/resize), and using Web Workers for heavy computations.

Tools like Chrome DevTools (Memory tab, Performance tab) are essential for profiling. Heap snapshots help identify what's taking up memory, while the Performance tab visualizes the main thread's activity.

Key Concepts

  • Garbage Collection (Mark-and-Sweep).
  • Memory Leaks & Prevention.
  • Event Loop & Main Thread blocking.
  • Debouncing vs. Throttling.
  • Web Workers for multi-threading.

Learning Objectives

Master

  • Identifying memory leaks with DevTools
  • Implementing debounce and throttle functions
  • Offloading heavy tasks to Web Workers
  • Optimizing DOM operations

Develop

  • Profiling application performance
  • Writing efficient loops and algorithms
  • Understanding browser rendering pipeline

Tips

  • Use `WeakMap` and `WeakSet` for caching objects without preventing garbage collection.
  • Always clear intervals (`clearInterval`) and timeouts (`clearTimeout`) when they are no longer needed.
  • Use `virtualization` (e.g., react-window) when rendering huge lists.
  • Avoid layout thrashing by reading layout properties (like `offsetHeight`) before writing to the DOM.

Common Pitfalls

  • Assuming the garbage collector will fix everything (it can't fix logic errors).
  • Using `setInterval` for animations (use `requestAnimationFrame` instead).
  • Blocking the main thread with JSON.parse() on huge strings.
  • Premature optimization (measure first, then optimize).

Summary

  • Memory is finite; manage it well.
  • Leaks crash apps over time.
  • Performance = User Experience.
  • DevTools are your best friend.

Exercise

Create an event listener that properly removes itself to prevent memory leaks.

function handleClick() {
  console.log('Button clicked!');
  // Remove the listener after first click
  button.removeEventListener('click', handleClick);
}

button.addEventListener('click', handleClick);

Exercise Tips

  • Use AbortController for modern event listener cleanup: const controller = new AbortController(); button.addEventListener('click', handler, { signal: controller.signal }); controller.abort();
  • Implement debounce to limit function calls: function debounce(fn, delay) { ... }.
  • Use requestAnimationFrame for smooth animations instead of setInterval.
  • Profile memory usage in Chrome DevTools to identify leaks.

Code Editor

Output