性能分析与内存泄漏检测
学习如何测量 Node.js 中的 CPU 与内存使用情况、捕获性能分析数据,并在内存泄漏导致生产环境崩溃前找出问题
性能分析与内存泄漏检测 是 CoddyKit 上的免费 Node.js Backend Development Bootcamp 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Node.js Backend Development Bootcamp 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Node.js Backend Development Bootcamp 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Why Profile?
You cannot optimize what you cannot measure. Profiling reveals where your app spends time (CPU) and memory, so you fix the real bottleneck instead of guessing.
A common rule: measure, change one thing, measure again.
Measuring Memory Usage
Node exposes live memory stats via process.memoryUsage(). The key field is heapUsed — the JavaScript heap your code allocates.
const m = process.memoryUsage();
console.log('Heap used MB:', (m.heapUsed / 1048576).toFixed(1));What is a Memory Leak?
A memory leak happens when objects that are no longer needed are still referenced, so the garbage collector cannot free them. Over time heapUsed climbs and the process eventually crashes.
Common Leak Sources
Most Node.js leaks come from a handful of patterns:
- Growing global arrays or caches that never evict
- Forgotten event listeners
- Closures capturing large objects
- Timers that are never cleared
const cache = [];
app.get('/x', (req, res) => {
cache.push(req.body); // never cleared = leak
res.end();
});Timing Code Sections
For quick CPU timing, console.time and console.timeEnd measure how long a block takes.
console.time('work');
for (let i = 0; i < 1e6; i++) {}
console.timeEnd('work');High-Resolution Timing
For precise benchmarks use the Performance API, which gives sub-millisecond resolution unaffected by clock changes.
const { performance } = require('perf_hooks');
const start = performance.now();
doWork();
console.log('Took', performance.now() - start, 'ms');CPU Profiling with --prof
Run Node with the --prof flag to record a V8 CPU profile. It writes a log file you process into a readable report.
// node --prof app.js
// node --prof-process isolate-*.log > report.txtHeap Snapshots
A heap snapshot captures every object in memory at a moment. Take two snapshots over time and compare them to find what keeps growing.
Capture them via Chrome DevTools (connect with --inspect) or programmatically.
// node --inspect app.js
// then open chrome://inspect and take heap snapshotsThe Clinic.js Toolkit
The clinic tool suite visualizes performance problems. Clinic Doctor diagnoses issues, while Clinic Heap Profiler tracks allocations.
// npm install -g clinic
// clinic doctor -- node app.jsDetecting a Leak in Practice
Log heapUsed periodically under steady load. If it trends upward and never returns after garbage collection, you likely have a leak — then snapshot to find the culprit.
setInterval(() => {
const mb = process.memoryUsage().heapUsed / 1048576;
console.log('Heap MB:', mb.toFixed(1));
}, 5000);Fixing Leaks
Once found, common fixes are:
- Cap caches with an LRU strategy
- Remove listeners with
removeListener/off - Clear timers with
clearInterval - Avoid capturing large objects in long-lived closures
Quick Check
Test your profiling knowledge.
Recap
You learned to profile and find leaks:
- Measure memory with
process.memoryUsage() - Time code with
console.timeand the Performance API - Capture CPU profiles with
--profand heap snapshots with--inspect - Spot leaks via climbing
heapUsed; fix with bounded caches and cleaned-up listeners/timers
Measuring first turns optimization from guesswork into engineering.
常见问题解答
「性能分析与内存泄漏检测」课时是免费的吗?
是的 — 「性能分析与内存泄漏检测」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Node.js Backend Development Bootcamp 课程的其余内容,请升级到 CoddyKit PRO。 Node.js Backend Development Bootcamp 课程共包含 4 节课。
「性能分析与内存泄漏检测」这节课中我会学到什么?
学习如何测量 Node.js 中的 CPU 与内存使用情况、捕获性能分析数据,并在内存泄漏导致生产环境崩溃前找出问题 你通过在浏览器中直接运行的动手代码来练习 Node.js Backend Development Bootcamp,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Node.js Backend Development Bootcamp 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Node.js Backend Development Bootcamp 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「性能分析与内存泄漏检测」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Node.js Backend Development Bootcamp 课中编写并运行代码吗?
能。每节 Node.js Backend Development Bootcamp 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。