Chuyển đến nội dung chính

レッスン 18: パフォーマンスのプロファイリングと最適化

V8 プロファイラ、--prof フラグ、フレームグラフ。メモリ リークの検出、ヒープ スナップショット。 Clinic.js (Doctor、Bubbleprof、Flame)。イベントループラグモニタリング、0xプロファイラ。 GCチューニング。

💻 プログラミング — レッスン 18 レッスン 18: パフォーマンス プロファイリングと 最適化

Node.js コア: 基本から高度まで

パート 5: テスト、パフォーマンス、および実稼働

xdev.asia

1. V8プロファイラー

# CPU profiling
node --prof app.js
# Tạo isolate-*.log
node --prof-process isolate-0x*.log > processed.txt

# Flamegraph với 0x
npx 0x app.js
# Mở browser tại flamegraph output

2. クリニック.js

# Clinic Doctor — phân tích tổng quát
npx clinic doctor -- node app.js
# Output: HTML report với CPU, memory, event loop, handles

# Clinic Flame — flamegraph
npx clinic flame -- node app.js
# Output: Interactive flamegraph

# Clinic Bubbleprof — async visualization
npx clinic bubbleprof -- node app.js
# Output: Async flow visualization

3. メモリリークの検出

import v8 from 'node:v8'

// Heap snapshot
v8.writeHeapSnapshot() // Tạo file .heapsnapshot → mở trong Chrome DevTools

// Programmatic monitoring
function monitorMemory() {
  const { heapUsed, heapTotal, external, rss } = process.memoryUsage()
  return {
    heapUsed: Math.round(heapUsed / 1e6),
    heapTotal: Math.round(heapTotal / 1e6),
    external: Math.round(external / 1e6),
    rss: Math.round(rss / 1e6),
  }
}

// Detect memory growth
let lastHeap = 0
setInterval(() => {
  const { heapUsed } = monitorMemory()
  const growth = heapUsed - lastHeap
  if (growth > 10) console.warn(`Memory grew by ${growth}MB`)
  lastHeap = heapUsed
}, 30000)

4. イベントループラグ

import { monitorEventLoopDelay } from 'node:perf_hooks'

const histogram = monitorEventLoopDelay({ resolution: 20 })
histogram.enable()

setInterval(() => {
  console.log({
    min: (histogram.min / 1e6).toFixed(2) + 'ms',
    max: (histogram.max / 1e6).toFixed(2) + 'ms',
    mean: (histogram.mean / 1e6).toFixed(2) + 'ms',
    p99: (histogram.percentile(99) / 1e6).toFixed(2) + 'ms',
  })
  histogram.reset()
}, 10000)

5. GC チューニング

# Xem GC events
node --trace-gc app.js

# GC flags
node --max-old-space-size=4096 \
     --max-semi-space-size=64 \
     --optimize-for-size \
     app.js

# Expose GC cho manual trigger (chỉ dev/debugging)
node --expose-gc -e "global.gc(); console.log(process.memoryUsage())"

6. 最適化チェックリスト

技術的な影響いつ
バッファの代わりにストリーム高大きなファイルの処理
接続プーリング高データベース/Redis接続
キャッシュ (Redis/LRU)高頻繁に読む
ワーカースレッド平均CPU を集中的に使用するタスク
クラスターモード平均マルチコアの利用
ネイティブアドオン高暗号、画像処理

次の記事: Docker と CI/CD — マルチステージビルド、GitHub Actions。