Performance: In-memory caching patterns
This affects server response time and CPU usage by reducing repeated data processing or fetching delays.
const cache = new Map(); async function getUser(id) { if (cache.has(id)) return cache.get(id); const user = await db.query(`SELECT * FROM users WHERE id = ${id}`); cache.set(id, user); return user; }
async function getUser(id) { const user = await db.query(`SELECT * FROM users WHERE id = ${id}`); return user; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No caching (fetch every time) | N/A (server-side) | N/A | N/A | [X] Bad |
| In-memory caching with Map | N/A (server-side) | N/A | N/A | [OK] Good |
const cache = new Map();
cache.set('user1', {name: 'Alice'});
cache.set('user2', {name: 'Bob'});
console.log(cache.get('user1').name);const cache = new Map();
function getData(key) {
if (cache.has(key)) {
return cache.get;
}
const data = fetchFromDb(key);
cache.set(key, data);
return data;
}Pass the test and this pattern moves unknown