JS Performance
Most JS performance work isn't about the language — it's about avoiding extra work, blocking the main thread, and shipping less code. Profile before you optimise.
The biggest wins, in order
- Ship less JavaScript. Code-split. Tree-shake. Defer non-critical scripts.
- Keep async work off the critical path. Hydrate later, lazy-load components.
- Batch DOM reads / writes. Reading layout (
offsetTop) after a write forces a re-layout. - Use the right data structure.
Mapbeats array search for membership;Setdedupes in O(1). - Cache expensive computations. Memoize pure functions.
Common micro-pitfalls
| Pattern | Why it's slow |
|---|---|
Sequential await on independent calls | Forces serial waterfall — use Promise.all. |
Math.max(...hugeArray) | Spreads onto the stack — can overflow. |
| Setting many properties in a loop on a styled element | Forces layout each time. Batch into a class swap. |
| Recreating regex inside a loop | Move the literal outside. |
| JSON.parse / stringify in a hot loop | Slow allocation — use objects directly when possible. |
String concatenation with + in a loop | Use arr.join("") or a string builder. |
Measure, don't guess
JS
console.time("hot loop");
for (let i = 0; i < 1e6; i++) /* … */;
console.timeEnd("hot loop");
// performance.now() — high-resolution timer
const start = performance.now();
work();
const elapsed = performance.now() - start;
// Tag intervals visible in the Performance panel
performance.mark("paint:start");
paint();
performance.mark("paint:end");
performance.measure("paint", "paint:start", "paint:end");
Network beats CPU
| Win | How |
|---|---|
| Brotli/gzip your assets | 5–10× smaller text payloads. |
| HTTP caching | Long max-age on hashed filenames. |
| Image formats | WebP / AVIF over JPG / PNG. |
| Preload critical fonts and JS | <link rel="preload">. |
Tip: Open Chrome's Performance panel and record a real interaction. The flame chart almost always points at the actual hot spot — which is rarely where you'd guess.
Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS Performance!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Run two independent fetches in parallel.
const [a, b] = await Promise.
([fetch('/a'), fetch('/b')]);
Three letters — fail-fast combinator.
Discussion
Loading…