Performance: Why caching matters
Caching improves page load speed and reduces server response time by storing data closer to the user or in memory.
const cache = new Map(); app.get('/data', async (req, res) => { if (cache.has('data')) { return res.json(cache.get('data')); } const data = await fetchFromDatabase(); cache.set('data', data); res.json(data); });
app.get('/data', async (req, res) => { const data = await fetchFromDatabase(); res.json(data); });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No caching, fetch on every request | N/A | N/A | High due to slow data arrival | [X] Bad |
| In-memory caching for repeated data | N/A | N/A | Low, data served instantly | [OK] Good |
const cache = new Map();
function getData(key) {
if (cache.has(key)) {
return cache.get(key);
}
const value = key * 2;
cache.set(key, value);
return value;
}
console.log(getData(5));
console.log(getData(5));
What will be printed to the console?const cache = new Map();
function fetchData(key) {
if (cache[key]) {
return cache[key];
}
const result = key + 100;
cache[key] = result;
return result;
}
What is the main problem with this caching approach?Pass the test and this pattern moves unknown