Chapter 5: Performance Optimization
Chapter 5 of 15
Chapter 5: Performance Optimization
5.1 Profiling
Profiling helps identify performance bottlenecks in your Node.js applications.
// Using built-in profiler
// node --prof app.js
// Generates isolate-*.log file
// node --prof-process isolate-*.log
// Using Chrome DevTools
// node --inspect app.js
// Open chrome://inspect in Chrome
// Using clinic.js
// npm install -g clinic
// clinic doctor -- node app.js
// clinic flame -- node app.js
// clinic bubbleprof -- node app.js
5.2 Memory Profiling
// Heap snapshot
const v8 = require('v8');
const heapSnapshot = v8.writeHeapSnapshot('heap-${Date.now()}.heapsnapshot');
// Analyze in Chrome DevTools
// chrome://inspect -> Memory tab -> Load snapshot
// Memory usage monitoring
const used = process.memoryUsage();
for (let key in used) {
console.log(`${key} ${Math.round(used[key] / 1024 / 1024 * 100) / 100} MB`);
}
5.3 CPU Profiling
// CPU profiling with perf
// perf record -e cycles:u -g -- node app.js
// perf report
// Using 0x (flamegraph generator)
// npm install -g 0x
// 0x app.js
5.4 Optimization Techniques
// 1. Use connection pooling
const pool = mysql.createPool({
connectionLimit: 10,
host: 'localhost',
user: 'user',
password: 'password',
database: 'mydb'
});
// 2. Cache frequently accessed data
const NodeCache = require('node-cache');
const cache = new NodeCache({ stdTTL: 600 });
function getCachedData(key) {
let data = cache.get(key);
if (!data) {
data = fetchDataFromDB(key);
cache.set(key, data);
}
return data;
}
// 3. Use streaming for large data
// Instead of loading entire file into memory
fs.createReadStream('large-file.txt')
.pipe(transformStream)
.pipe(fs.createWriteStream('output.txt'));