[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,93 +2,210 @@
|
||||
id: wiki-2026-0508-memory-leak-debugging-in-javascr
|
||||
title: Memory Leak Debugging in JavaScript
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [FE-DEBUG-memory-001]
|
||||
aliases: [JS Memory Leak, Heap Leak Debugging]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: ["JavaScript|[JavaScript", performance, debugging, memory-leak, heap-snapshot, devtools, Chrome]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [javascript, performance, debugging, memory]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-26
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: JavaScript
|
||||
framework: Chrome DevTools
|
||||
---
|
||||
|
||||
# Memory Leak Debugging in JavaScript (자바스크립트 메모리 누수 디버깅)
|
||||
# Memory Leak Debugging in JavaScript
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "더 이상 필요하지 않은 데이터가 가비지 컬렉터(GC)에 의해 회수되지 않고 점유되는 현상을 추적하고, 브라우저 힙(Heap)의 비정상적 비대를 사전에 차단하여 런타임 안정성을 확보하라" — 장기 세션 애플리케이션의 성능 저하와 크래시를 방지하는 고도의 디버깅 기술.
|
||||
## 매 한 줄
|
||||
> **"매 unintended retention — 매 GC 매 reach 가능한 reference chain 매 끊지 못해 매 heap 매 grows unbounded"**. JS 매 mark-and-sweep GC 자동이지만 매 closure/listener/global/timer 매 long-lived reference 매 object lifecycle 매 의도와 분리시키면 매 leak 발생, 매 Chrome DevTools Heap Snapshot 매 진단 standard.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **추출된 패턴:** "Snapshot Comparison and [[Reference|Reference]] Tracking" — 특정 시점의 메모리 스냅샷을 비교하여 해제되지 않은 객체와 그 참조 경로를 식별하는 패턴.
|
||||
- **주요 원인 및 해결책:**
|
||||
- **Global Variables:** 의도치 않게 전역 객체에 할당된 변수 제거.
|
||||
- **Forgotten Timers/Listeners:** 컴포넌트 언마운트 시 `clearTimeout`이나 `removeEventListener`를 호출하지 않아 발생하는 누수.
|
||||
- **Closures:** 상위 스코프의 변수를 불필요하게 오래 점유하는 클로저 식별.
|
||||
- **Detached DOM Nodes:** DOM에서는 삭제되었으나 JS 변수가 참조하고 있어 메모리에 남아있는 노드 제거.
|
||||
- **디버깅 도구 활용:**
|
||||
- **[[Chrome DevTools|Chrome DevTools]] Memory Tab:** [[Heap Snapshot|Heap Snapshot]]을 찍어 객체 수 증가 추이 확인.
|
||||
- **Allocation Instrumentation on Timeline:** 메모리 할당이 발생하는 시점 실시간 관측.
|
||||
- **Performance Monitor:** CPU와 메모리 사용량 실시간 모니터링.
|
||||
- **의의:** 애플리케이션의 점진적 속도 저하(Sluggishness)를 방지하고, 사용자에게 일관된 쾌적함을 제공함.
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 과거에는 메모리 누수를 드문 현상으로 여겼으나, 현대의 복잡한 SPA 환경에서는 세션이 길어짐에 따라 '누적되는 누수 정책'이 심각한 사용자 경험 저하를 유발함.
|
||||
- **정책 변화:** Antigravity 프로젝트는 모든 복잡한 위젯(차트, 에디터 등) 개발 시 언마운트 후 메모리 잔류 여부 테스트를 필수 정책으로 하며, 메모리 사용량이 임계치 이상 상승할 경우 자동 경고 정책을 시행함.
|
||||
### 매 leak sources (top 5)
|
||||
- **Detached DOM nodes**: 매 element removed from tree 매 JS reference 잔존.
|
||||
- **Event listeners**: 매 addEventListener 매 removeEventListener 없이 매 component unmount.
|
||||
- **Timers**: setInterval/setTimeout 매 cleanup 누락 매 closure 매 모두 retain.
|
||||
- **Closures**: outer scope variables 매 inner function 매 capture 후 매 long-lived.
|
||||
- **Global accumulation**: window/globalThis 매 cache/array 매 unbounded push.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[Frontend-Debugging-and-Testing|Frontend-Debugging-and-Testing]], JavaScript-Optimization-Patterns, React-Error-Boundaries-and-Handling, [[Frontend-Performance-Optimization-Guide|Frontend-Performance-Optimization-Guide]]
|
||||
- **Raw Source:** 00_Raw/Memory Leak Debugging.md
|
||||
### 매 detection tools
|
||||
- **Chrome DevTools Memory**: Heap snapshot, allocation timeline, allocation sampling.
|
||||
- **performance.measureUserAgentSpecificMemory()** (Chrome 89+): 매 cross-origin isolated context.
|
||||
- **Node.js**: --inspect + Chrome DevTools, heapdump module, --heap-prof flag.
|
||||
- **WeakRef + FinalizationRegistry**: 매 GC 관찰 (debugging only).
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 응용
|
||||
1. SPA 매 route navigation 매 retain leak 진단.
|
||||
2. Long-running dashboard 매 hour-scale leak 감시.
|
||||
3. Node.js server 매 RSS growth 매 root cause.
|
||||
4. React/Vue component lifecycle leak detection.
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
## 💻 패턴
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
### Heap snapshot 3-snapshot technique
|
||||
```
|
||||
1. App 초기 load → Snapshot 1 (baseline)
|
||||
2. Suspect action 수행 (modal open/close ×10) → Snapshot 2
|
||||
3. 동일 action 재수행 → Snapshot 3
|
||||
4. Snapshot 3 의 Comparison → Snapshot 1
|
||||
5. "Allocated between snapshots 1 and 3" 의 still-alive objects = leak
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Detached DOM 탐색 (DevTools Console)
|
||||
```js
|
||||
// Heap snapshot Class filter:
|
||||
// "Detached HTMLDivElement"
|
||||
// "Detached HTMLElement"
|
||||
// 매 instance 매 retainer chain 매 inspect — 매 root retainer 매 leak 출처
|
||||
```
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Event listener leak — fix pattern
|
||||
```js
|
||||
// 매 BAD
|
||||
class Widget {
|
||||
constructor() {
|
||||
window.addEventListener('resize', this.onResize.bind(this));
|
||||
}
|
||||
onResize() { /* ... */ }
|
||||
destroy() { /* listener still attached */ }
|
||||
}
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
// 매 GOOD
|
||||
class Widget {
|
||||
constructor() {
|
||||
this.onResize = this.onResize.bind(this);
|
||||
window.addEventListener('resize', this.onResize);
|
||||
}
|
||||
onResize() { /* ... */ }
|
||||
destroy() {
|
||||
window.removeEventListener('resize', this.onResize);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### AbortController 매 modern cleanup
|
||||
```js
|
||||
class Component {
|
||||
constructor() {
|
||||
this.ac = new AbortController();
|
||||
const { signal } = this.ac;
|
||||
window.addEventListener('scroll', this.onScroll, { signal });
|
||||
window.addEventListener('resize', this.onResize, { signal });
|
||||
fetch('/api', { signal });
|
||||
}
|
||||
destroy() {
|
||||
this.ac.abort(); // 매 모든 listener + fetch 매 한 번에 cleanup
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### Timer leak fix
|
||||
```js
|
||||
// 매 BAD — closure captures large data
|
||||
function startPolling(bigData) {
|
||||
setInterval(() => {
|
||||
console.log(bigData.length); // bigData retained forever
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
// 매 GOOD — explicit handle + cleanup
|
||||
const handle = setInterval(poll, 1000);
|
||||
function stop() { clearInterval(handle); }
|
||||
```
|
||||
|
||||
### WeakMap 매 cache without leak
|
||||
```js
|
||||
// 매 BAD — Map 매 key 매 GC X
|
||||
const cache = new Map();
|
||||
function getMeta(node) {
|
||||
if (!cache.has(node)) cache.set(node, computeMeta(node));
|
||||
return cache.get(node); // node removed from DOM but still in cache
|
||||
}
|
||||
|
||||
// 매 GOOD — WeakMap key 매 GC 가능
|
||||
const cache = new WeakMap();
|
||||
function getMeta(node) {
|
||||
if (!cache.has(node)) cache.set(node, computeMeta(node));
|
||||
return cache.get(node);
|
||||
}
|
||||
```
|
||||
|
||||
### performance.measureUserAgentSpecificMemory
|
||||
```js
|
||||
// crossOriginIsolated context (COOP+COEP headers) 필요
|
||||
if (crossOriginIsolated && performance.measureUserAgentSpecificMemory) {
|
||||
const result = await performance.measureUserAgentSpecificMemory();
|
||||
console.log('bytes:', result.bytes);
|
||||
console.table(result.breakdown);
|
||||
}
|
||||
```
|
||||
|
||||
### FinalizationRegistry 매 GC 관찰 (debug only)
|
||||
```js
|
||||
const registry = new FinalizationRegistry((tag) => {
|
||||
console.log(`GC'd: ${tag}`);
|
||||
});
|
||||
|
||||
class Tracked {
|
||||
constructor(name) {
|
||||
registry.register(this, name);
|
||||
}
|
||||
}
|
||||
|
||||
new Tracked('widget-1'); // → "GC'd: widget-1" eventually (or never)
|
||||
```
|
||||
|
||||
### Node.js heap snapshot
|
||||
```bash
|
||||
node --inspect server.js
|
||||
# 매 chrome://inspect → Memory → Take heap snapshot
|
||||
# 또는 programmatic:
|
||||
```
|
||||
```js
|
||||
import { writeHeapSnapshot } from 'node:v8';
|
||||
const path = writeHeapSnapshot(); // .heapsnapshot file
|
||||
console.log(`Snapshot: ${path}`);
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Tool/Approach |
|
||||
|---|---|
|
||||
| Browser SPA growing memory | DevTools Heap Snapshot 3-snapshot |
|
||||
| 매 frame allocation hotspot | Allocation timeline (sampling) |
|
||||
| Detached DOM 의심 | Class filter "Detached " in snapshot |
|
||||
| Node.js RSS growth | writeHeapSnapshot + Chrome DevTools |
|
||||
| Continuous monitoring (production) | performance.measureUserAgentSpecificMemory |
|
||||
| Event listener leak | AbortController 매 unified cleanup |
|
||||
|
||||
**기본값**: 매 Heap Snapshot 3-snapshot diff — 매 retainer chain 매 따라 root 매 식별.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[JavaScript-Performance]] · [[Garbage-Collection]]
|
||||
- 변형: [[Node-js-Memory-Profiling]] · [[V8-Heap-Analysis]]
|
||||
- 응용: [[SPA-Performance]] · [[Long-Running-Apps]]
|
||||
- Adjacent: [[Chrome-DevTools]] · [[WeakMap]] · [[AbortController]] · [[FinalizationRegistry]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 SPA/long-running app 의 메모리 증가, 매 unmount 후 referent 잔존, 매 production memory metrics 의 anomaly.
|
||||
**언제 X**: 매 short-lived script (CLI tool), 매 GC pause 문제 (different — GC tuning territory).
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **`delete` keyword 의존**: 매 reference 매 nullify 안 함 — 매 다른 reference 매 retain.
|
||||
- **`window.gc()` 매 production**: 매 only with --expose-gc flag, 매 hint 일 뿐.
|
||||
- **Allocation timeline 매 production trace**: 매 overhead 매 큼 — 매 staging 에서.
|
||||
- **One-snapshot 진단**: 매 baseline 없으면 매 noise 와 leak 매 구분 불가.
|
||||
- **DevTools 매 incognito 가정**: 매 extension 매 heap pollution — 매 incognito + 매 disabled extensions.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Chrome DevTools docs, V8 blog, Node.js v8 module).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — leak source taxonomy + DevTools workflow + AbortController/WeakMap patterns |
|
||||
|
||||
Reference in New Issue
Block a user