Memory Leak
快速摘要
你的 program keeps allocating memory 不使用 releasing 它 — over 时间, memory usage grows 直到 program slows or crashes.
为什么发生
引用到 对象是 kept in 全局变量 or caches 那个从不清晰
事件监听器是 添加但 从不移除
闭包 capture 变量那个 prevent garbage 集合
最小示例
✗ 错误代码
const cache = [];
function process(item) {
cache.push(item); // Never cleared — grows forever!
return item.value;
}✓ 修复代码
const cache = new Map();
function process(item) {
cache.set(item.id, item);
if (cache.size > 1000) {
// Clear old entries to bound memory
const firstKey = cache.keys().next().value;
cache.delete(firstKey);
}
return item.value;
}缓存数组 grows 不使用边界, leaking memory. Using 映射使用大小限制 and 移除旧 条目边界 memory usage 虽然 still 缓存 recent 项.
如何诊断
Monitor memory usage over 时间 — 做它 keep growing?
Use 浏览器 DevTools memory profiler 到查找 retained 对象
Look for 全局变量, caches, or 事件监听器那个 accumulate
如何修复
移除引用到 对象当 它们是 否 longer 需要
移除事件监听器使用 removeEventListener 当元素是 destroyed
Use WeakMap/WeakSet for caches 那个允许 garbage 集合
如何预防
总是 clean 上事件监听器, timers, and subscriptions
Avoid 全局变量 for 存储数据
Use weak 引用 for caches
相关资源
相关术语
相关课程
- Memory and 引用
学习关于 memory management.