Skip to content

浏览器 Memory Leak

快速摘要

你的 web page 获取 slower over 时间因为 JavaScript 是持有引用到 对象那个应该是 garbage collected.

为什么发生

  • 事件监听器不 移除当 元素是 移除从 DOM

  • Intervals and timeouts 不 cleared 当否 longer 需要

  • 闭包持有引用到 大对象 unnecessarily

  • 全局变量 accumulating 数据不使用 cleanup

最小示例

✗ 错误代码
function setup() {
  const el = document.querySelector(".btn");
  el.addEventListener("click", () => {
    console.log("clicked");
  });
  // If el is removed from DOM, the listener and closure persist
  // Memory leak: el and its closure are never garbage collected
}
✓ 修复代码
function setup() {
  const el = document.querySelector(".btn");
  const handler = () => console.log("clicked");
  el.addEventListener("click", handler);
  // Return a cleanup function
  return () => el.removeEventListener("click", handler);
}
// Call cleanup when the element is removed

存储处理函数引用 and 返回 cleanup 函数那个移除事件监听器. Call cleanup 当元素是 移除从 DOM 到 prevent memory leak.

如何诊断

  • Use DevTools Memory tab — take heap snapshots and compare

  • Use 性能 Monitor 到 watch JS heap 大小 over 时间

  • Look for detached DOM 节点 in heap snapshot

如何修复

  • 移除事件监听器使用 removeEventListener 当元素是 移除

  • 清晰 intervals and timeouts 使用 clearInterval/clearTimeout

  • 设置引用到 空当 否 longer 需要

  • Use WeakMap/WeakSet for 引用那个应该不 prevent garbage 集合

如何预防

  • 总是 clean 上事件监听器, intervals, and timeouts

  • Avoid 全局变量 — use 模块 and 闭包 properly

  • Use weak 引用 for 数据那个能 是 garbage collected

相关资源

相关术语

相关课程

← 返回语言