Performance: Why caching improves performance
Caching reduces server response time and network load, improving page load speed and interaction responsiveness.
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, fast data delivery | [OK] Good |
app.get('/data', (req, res) => {
if (cache.data) {
res.send(cache.data);
} else {
const result = expensiveCalculation();
cache.data = result;
res.send(result);
}
});
What happens on the second request to '/data'?app.get('/info', (req, res) => {
if (cache.info) {
res.send(cache.info);
} else {
const data = fetchData();
cache.info = data;
res.send(data);
}
});
fetchData() is asynchronous and returns a Promise. What is the main issue?Pass the test and this pattern moves unknown