Performance: Memory management best practices
This concept affects server-side memory usage and response time, impacting how quickly Node.js can handle requests without slowing down or crashing.
const cache = new Map();
function handleRequest(data) {
cache.set(data.id, data);
if (cache.size > 1000) {
const firstKey = cache.keys().next().value;
cache.delete(firstKey);
}
}const cache = {};
function handleRequest(data) {
cache[data.id] = data;
// never delete or clear cache
}| Pattern | Memory Usage | Garbage Collection Frequency | Response Time Impact | Verdict |
|---|---|---|---|---|
| Unbounded cache without cleanup | High and growing | Frequent and long pauses | Slower and unstable | [X] Bad |
| Bounded cache with cleanup | Stable and limited | Infrequent and short pauses | Fast and stable | [OK] Good |
const data = [];
setInterval(() => {
data.push(new Array(1000000).fill('x'));
console.log('Data length:', data.length);
}, 1000);
let cache = {};
function addToCache(key, value) {
cache[key] = value;
}
setInterval(() => {
addToCache(Date.now(), new Array(1000000).fill('leak'));
}, 1000);
Pass the test and this pattern moves unknown