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

第 18 課:效能分析與最佳化

V8 分析器,--prof 標誌,火焰圖。記憶體洩漏檢測、堆快照。 Clinic.js(Doctor、Bubbleprof、Flame)。事件循環滯後監控,0x 分析器。 GC 調諧。

💻 程式設計 — 第 18 課 第 18 課:表現分析與 最佳化

Node.js 核心:從基礎到高級

第 5 部分:測試、性能和生產

亞洲開發網

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.Clinic.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。