JavaScript Performance
Micro-optimizations for high-performance JavaScript.
Instructions
- Use Set for Lookups
// ❌ Bad - O(n) lookup const ids = [1, 2, 3, 4, 5]; if (ids.includes(targetId)) { ... }
// ✅ Good - O(1) lookup const idSet = new Set([1, 2, 3, 4, 5]); if (idSet.has(targetId)) { ... }
- Use Map for Key-Value
// ❌ Bad - object for dynamic keys const cache: { [key: string]: Data } = {}; cache[key] = data;
// ✅ Good - Map for dynamic keys const cache = new Map<string, Data>(); cache.set(key, data);
- Early Returns
// ❌ Bad - nested conditions function process(data) { if (data) { if (data.isValid) { if (data.type === 'user') { return handleUser(data); } } } return null; }
// ✅ Good - early returns function process(data) { if (!data) return null; if (!data.isValid) return null; if (data.type !== 'user') return null; return handleUser(data); }
- Avoid Creating Arrays
// ❌ Bad - creates intermediate array const result = items.filter(x => x.active).map(x => x.name)[0];
// ✅ Good - find first match const result = items.find(x => x.active)?.name;
- Batch DOM Updates
// ❌ Bad - multiple reflows items.forEach(item => { const el = document.createElement('div'); el.textContent = item.name; container.appendChild(el); });
// ✅ Good - single reflow const fragment = document.createDocumentFragment(); items.forEach(item => { const el = document.createElement('div'); el.textContent = item.name; fragment.appendChild(el); }); container.appendChild(fragment);
- Passive Event Listeners
// ✅ Use passive for scroll/touch events element.addEventListener('scroll', handler, { passive: true }); element.addEventListener('touchstart', handler, { passive: true });
- Caching Expensive Operations
// ✅ Memoization const cache = new Map();
function expensiveCalculation(input: string) { if (cache.has(input)) { return cache.get(input); } const result = /* expensive operation */; cache.set(input, result); return result; }
- Object Spread vs Object.assign
// ✅ For small objects - spread is fine const merged = { ...a, ...b };
// ✅ For large objects - Object.assign is faster const merged = Object.assign({}, a, b);
References
-
JavaScript Performance
-
V8 Blog