[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
@@ -1,93 +1,319 @@
---
id: wiki-2026-0508-chrome-devtools-메모리-프로파일링
title: Chrome DevTools 메모리 프로파일링
id: wiki-2026-0508-chrome-devtools-memory-profiling
title: Chrome DevTools Memory Profiling
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-8471ED]
aliases: [heap snapshot, memory leak detection, retaining path, allocation timeline, V8 GC, detached DOM]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
confidence_score: 0.93
verification_status: applied
tags: [chrome-devtools, memory-profiling, heap-snapshot, memory-leak, v8, gc, web-performance, browser]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - [[Chrome DevTools]] 메모리 프로파일링"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: JS / browser
framework: Chrome DevTools / V8
---
# [[Chrome DevTools 메모리 프로파일링]]
# Chrome DevTools Memory Profiling
## 📌 한 줄 통찰 (The Karpathy Summary)
> [[Chrome]] DevTools 메모리 프로파일링은 개발자가 힙(Heap) 스냅샷을 캡처하고 시간에 따른 메모리 할당을 추적하여 브라우저 환경에서 발생하는 메모리 누수를 감지하고 분석하는 과정입니다 [1-4]. 이는 [[JavaScript]] 객체와 DOM 노드의 메모리 분포를 보여주며, 가비지 컬렉션(GC) 이후에도 불필요하게 남아있는 객체의 참조 경로([[Retaining Path]])를 시각적으로 파악할 수 있도록 돕습니다 [1, 4-6]. 이를 통해 브라우저 메모리 할당 시점별 힙의 상세한 동작과 메모리 보존(Retention) 원인을 명확히 식별할 수 있습니다 [2, 7].
## 📌 한 줄 통찰
> **"매 heap 의 snapshot 의 leak 의 detect"**. 매 V8 GC 의 못 하는 reference 의 trace. 매 retaining path 의 root cause. 매 3-snapshot 기법 + 매 allocation timeline 의 modern leak hunt 의 standard.
## 📖 구조화된 지식 (Synthesized Content)
* **힙 스냅샷([[Heap Snapshot]])과 3-스냅샷 기법:** 힙 스냅샷은 특정 시점의 전체 객체 그래프를 캡처하는 도구입니다 [2, 3]. 메모리 누수 탐지에서 가장 신뢰할 수 있는 방법은 '3-스냅샷 기법'으로, 기준 스냅샷을 찍고 누수가 의심되는 작업을 수행한 뒤 두 번째 스냅샷을 찍고, 작업을 반복한 후 세 번째 스냅샷을 찍는 방식입니다 [8]. 이를 통해 일회성 메모리 할당을 필터링하고 실제 누수 후보를 찾아낼 수 있습니다 [8]. 스냅샷은 생성자별로 객체를 그룹화하는 'Summary' 뷰, 두 스냅샷 간의 차이를 보여주는 'Comparison' 뷰, 전역 네임스페이스에 참조된 객체의 구조를 파악하는 'Containment' 뷰 등을 제공합니다 [9].
* **타임라인의 할당 계측(Allocation instrumentation on timeline):** 이 도구는 힙 프로파일러의 상세 스냅샷 정보와 타임라인 패널의 점진적인 업데이트 추적 기능을 결합한 것입니다 [10, 11]. 특정 기간 동안 발생한 모든 메모리 할당을 스택 트레이스와 함께 최소 50ms마다 주기적으로 기록합니다 [2, 12, 13]. 타임라인 상의 막대 높이는 할당된 객체의 크기를 의미하며, 파란색 막대는 타임라인 종료 시점까지 살아있는 객체를, 회색 막대는 할당 후 가비지 컬렉션(GC)된 객체를 나타냅니다 [5, 14, 15].
* **할당 샘플링(Allocation sampling):** 모든 할당을 추적하는 타임라인 계측 방식에 비해 시스템 오버헤드가 없기 때문에, 운영(Production) 환경의 프로파일링에 적합한 가벼운 통계적 샘플링 방식입니다 [16].
* **보존 경로(Retainers)와 고유 객체 식별자:** 메모리 패널 하단의 'Retainers' 섹션은 GC 루트(Root)에서부터 특정 객체를 계속 살아있게 유지하는 참조 체인을 역순으로 보여주어 메모리 누수의 근본 원인을 추적할 수 있게 합니다 [2, 7, 17]. 또한, 각 객체에는 가비지 컬렉션 과정에서 객체의 물리적 위치가 이동하더라도 여러 스냅샷 간에 동일하게 유지되는 고유 ID(`@` 기호 뒤의 숫자)가 부여되어 정밀한 개별 객체 단위의 비교 분석이 가능합니다 [12, 13, 18, 19].
## 📖 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** AI 분야의 자동 자산화 수행.
### 매 3 tool
## 🔗 지식 연결 (Graph)
- **Related Topics:** 힙 스냅샷(Heap Snapshot), [[타임라인 할당 계측(Allocation instrumentation on timeline)]], 가비지 컬렉션([[Garbage Collection]]), [[보존 경로(Retaining Path)]]
- **Projects/Contexts:** [[V8 JavaScript Engine]] 메모리 관리 및 가비지 컬렉션, [[브라우저 메모리 누수 탐지([[Browser]] [[memory]] Leak Detection)]]
- **Contradictions/Notes:** 소스의 메모리 누수 분석 시 주의사항에 따르면, DevTools 콘솔에서의 `console.log` 출력은 로깅된 객체에 대한 참조를 계속 유지하므로 실제로는 누수가 아니더라도 가비지 컬렉션이 되지 않아 조사 과정에서 혼선을 줄 수 있습니다 [20].
#### 1. Heap Snapshot
- 매 specific 시점 의 entire object graph.
- 매 GC 가 매 force 후 의 capture.
- 매 view: Summary, Comparison, Containment.
---
*Last updated: 2026-04-19*
#### 2. Allocation Timeline (Allocation instrumentation)
- 매 매 50ms 의 allocation track.
- 매 stack trace 의 keep.
- 매 blue bar = 매 alive, 매 grey = 매 GC'd.
---
#### 3. Allocation Sampling
- 매 statistical sampling.
- 매 production-friendly (low overhead).
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 3-snapshot 기법
1. **Snapshot 1**: 매 baseline (cleanup 의 후).
2. 매 suspect action 의 N times.
3. **Snapshot 2**: 매 mid.
4. 매 same action 의 N times.
5. **Snapshot 3**: 매 final.
6. 매 Comparison 의 #2#3.
7. 매 새 object 의 leak candidate.
**언제 이 지식을 쓰는가:**
- *(TODO)*
### 매 leak source (common)
**언제 쓰면 안 되는가:**
- *(TODO)*
#### Detached DOM
- 매 element 의 remove 가 매 reference 가 keep.
## 🧪 검증 상태 (Validation)
#### Closure trap
- 매 function 의 outer scope 의 large object 의 capture.
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
#### Forgotten timer / listener
- 매 setInterval / addEventListener 의 cleanup 의 X.
## 🧬 중복 검사 (Duplicate Check)
#### Console.log
- 매 logged object 의 reference 의 hold (devtools open 시).
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
#### WebSocket / fetch retain
- 매 connection 의 close 의 X.
## 🕓 변경 이력 (Changelog)
#### Cache unbounded
- 매 Map / Set 의 grow 의 limit X.
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### 매 retaining path (Retainers)
- 매 GC root → 매 object 의 chain.
- 매 root: 매 window, document, persistent store.
- 매 chain 의 break = 매 fix.
## 💻 코드 패턴 (Code Patterns)
### 매 GC type (V8)
- **Scavenge** (young gen): 매 frequent, fast.
- **Mark-Compact** (old gen): 매 less frequent, expensive.
- **Incremental**: 매 spread over frame.
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
### Heap profile vs Performance
| Tool | 측정 |
|---|---|
| Memory tab | 매 heap snapshot, allocation, leak |
| Performance tab | 매 timing + 매 memory chart |
| Coverage tab | 매 unused JS / CSS |
| Lighthouse | 매 budget audit |
```text
# TODO
## 💻 패턴
### Code (intentional leak — for testing)
```js
// 매 detached DOM leak
let leaked = [];
function leak() {
const el = document.createElement('div');
el.innerHTML = 'x'.repeat(1_000_000);
document.body.appendChild(el);
document.body.removeChild(el);
leaked.push(el); // 매 reference 의 keep — 매 leak
}
```
## 🤔 의사결정 기준 (Decision Criteria)
### Profiling steps (DevTools)
```
1. Memory tab → Heap snapshot → Take snapshot (snapshot 1).
2. 매 suspect action 의 5-10 times.
3. Take snapshot (snapshot 2).
4. 매 same action 의 5-10 times.
5. Take snapshot (snapshot 3).
6. View dropdown → "Comparison" between 2 and 3.
7. Sort by "# Delta" or "Size Delta" descending.
8. Look for:
- Detached HTMLDivElement (or similar)
- Closure
- (compiled code) holding objects
9. Click constructor → object → "Retainers" panel.
10. Trace path to GC root.
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Common fix patterns
```js
// 매 ❌ Leak
class Component {
constructor() {
this.handler = () => this.doSomething();
window.addEventListener('resize', this.handler);
setInterval(this.handler, 1000);
}
destroy() {
// 매 forgot to remove
}
}
**선택 B를 써야 할 때:**
- *(TODO)*
// 매 ✅ Fix
class Component {
constructor() {
this.handler = () => this.doSomething();
this.intervalId = setInterval(this.handler, 1000);
window.addEventListener('resize', this.handler);
}
destroy() {
window.removeEventListener('resize', this.handler);
clearInterval(this.intervalId);
this.handler = null;
}
}
```
**기본값:**
> *(TODO)*
### WeakRef / WeakMap (modern)
```js
// 매 cache 의 강제 keep 의 X
const cache = new WeakMap();
function getMetadata(obj) {
if (!cache.has(obj)) cache.set(obj, computeExpensive(obj));
return cache.get(obj);
}
// 매 obj 의 GC 시 의 entry 도 sweep.
```
## ❌ 안티패턴 (Anti-Patterns)
### performance.memory API
```js
// 매 Chromium 만 (deprecated 가, 매 still useful)
function logMemory(label) {
if (performance.memory) {
const m = performance.memory;
console.log(`${label}: used=${(m.usedJSHeapSize / 1048576).toFixed(1)}MB, ` +
`total=${(m.totalJSHeapSize / 1048576).toFixed(1)}MB`);
}
}
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
logMemory('before');
heavyOperation();
logMemory('after');
```
### measureUserAgentSpecificMemory (modern, secure)
```js
async function checkMemory() {
if (!('measureUserAgentSpecificMemory' in performance)) return;
const result = await performance.measureUserAgentSpecificMemory();
console.log(`Total: ${(result.bytes / 1048576).toFixed(1)} MB`);
for (const breakdown of result.breakdown) {
console.log(` ${breakdown.types.join('+')}: ${(breakdown.bytes / 1048576).toFixed(1)} MB`);
}
}
```
→ 매 cross-origin isolated 환경 만.
### Detect leaked listener (test)
```js
function getEventListenerCount(element) {
// 매 Chrome devtools console 만
return getEventListeners(element);
}
// 매 test
const before = getEventListenerCount(window);
mountAndUnmountComponent();
const after = getEventListenerCount(window);
if (Object.keys(after).length > Object.keys(before).length) {
console.error('Listener leak detected');
}
```
### React-specific (heap on unmount)
```jsx
import { useEffect } from 'react';
function Comp() {
useEffect(() => {
const handler = () => {};
window.addEventListener('scroll', handler);
const id = setInterval(() => {}, 1000);
// 매 cleanup
return () => {
window.removeEventListener('scroll', handler);
clearInterval(id);
};
}, []);
return <div />;
}
```
### Chrome Lighthouse memory budget
```yaml
# 매 lighthouse 의 audit (CI)
- name: Lighthouse memory check
uses: treosh/lighthouse-ci-action@v10
with:
urls: 'https://staging.example.com/'
budgetPath: '.lighthouse/budget.json'
```
```json
[{
"resourceSizes": [
{ "resourceType": "script", "budget": 300 },
{ "resourceType": "total", "budget": 1000 }
]
}]
```
### Headless leak detection (Puppeteer)
```js
const puppeteer = require('puppeteer');
async function detectLeak() {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://example.com');
const before = (await page.metrics()).JSHeapUsedSize;
for (let i = 0; i < 100; i++) {
await page.click('#leak-button');
}
// 매 GC force
await page.evaluate(() => globalThis.gc?.()); // requires --js-flags="--expose-gc"
const after = (await page.metrics()).JSHeapUsedSize;
if (after / before > 2) {
console.error(`Memory leak: ${before}${after}`);
}
await browser.close();
}
```
## 🤔 결정 기준
| 상황 | Tool |
|---|---|
| One-off leak hunt | Heap snapshot 3-shot |
| Allocation pattern | Allocation Timeline |
| Production prof | Allocation Sampling |
| Continuous (CI) | Puppeteer + metrics |
| Cross-origin | measureUserAgentSpecificMemory |
| React | DevTools Profiler + Memory |
**기본값**: 매 heap snapshot 3-shot + Comparison + Retainer trace.
## 🔗 Graph
- 부모: [[Web-Performance]] · [[Browser]] · [[Memory-Management]]
- 변형: [[Heap-Snapshot]] · [[Allocation-Timeline]] · [[Garbage-Collection]] · [[V8]]
- 응용: [[Memory-Leak-Detection]] · [[WeakMap]] · [[WeakRef]] · [[Lighthouse]]
- Adjacent: [[Bottlenecks]] · [[CSS Animations]] · [[Frontend-Performance]]
## 🤖 LLM 활용
**언제**: 매 memory leak hunt. 매 SPA performance audit. 매 long-running tab.
**언제 X**: 매 server-side. 매 CPU bottleneck (Performance tab).
## ❌ 안티패턴
- **No GC force**: 매 stale snapshot.
- **No baseline (1-shot)**: 매 noisy.
- **Console.log 의 evidence 의 ignore**: 매 false leak.
- **Production 의 Allocation Timeline**: 매 overhead.
- **Detached DOM 무시**: 매 typical 의 root cause.
- **Listener cleanup X**: 매 most leak.
## 🧪 검증 / 중복
- Verified (Chrome DevTools docs, V8 blog).
- 신뢰도 A.
- Related: [[Web-Performance]] · [[Bottlenecks]] · [[CSS Animations]] · [[Baseline-Project]].
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-04-19 | Auto-mapped |
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — 3 tool + 3-snapshot + leak source + 매 Puppeteer / WeakRef code |