Node.js Performance — Profiling and Optimization
Advertisement
Performance is critical. Profile, identify bottlenecks, optimize systematically.
Profiling
# CPU profiling
node --prof app.js
node --prof-process isolate-*.log > profile.txt
# Inspect
node --inspect app.js
# Open chrome://inspect
Memory Profiling
// Check memory
console.log(process.memoryUsage());
// {
// rss: 27.1 MB,
// heapTotal: 8.8 MB,
// heapUsed: 4.2 MB,
// external: 0.2 MB
// }
// Monitor
setInterval(() => {
const mem = process.memoryUsage();
console.log(`Memory: ${Math.round(mem.heapUsed / 1024 / 1024)}MB`);
}, 1000);
Optimization Tips
- Use clustering - Multi-core utilization
- Connection pooling - Reuse database connections
- Cache aggressively - Redis, memory cache
- Stream large files - Don't load into memory
- Compress responses - gzip middleware
- Use CDN - Static assets
FAQ
Q: How to find memory leaks? A: Profile heap, compare snapshots, use clinic.js.
Q: When to scale horizontally? A: When single node maxed out. Use load balancer.
Performance tuning is continuous. Profile regularly, optimize based on data.
Advertisement
← Previous
Node.js Streams — Complete Guide