iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

  1. Ship less JavaScript. Code-split. Tree-shake. Defer non-critical scripts.
  2. Keep async work off the critical path. Hydrate later, lazy-load components.
  3. Batch DOM reads / writes. Reading layout (offsetTop) after a write forces a re-layout.
  4. Use the right data structure. Map beats array search for membership; Set dedupes in O(1).
  5. Cache expensive computations. Memoize pure functions.

Common micro-pitfalls

PatternWhy it's slow
Sequential await on independent callsForces serial waterfall — use Promise.all.
Math.max(...hugeArray)Spreads onto the stack — can overflow.
Setting many properties in a loop on a styled elementForces layout each time. Batch into a class swap.
Recreating regex inside a loopMove the literal outside.
JSON.parse / stringify in a hot loopSlow allocation — use objects directly when possible.
String concatenation with + in a loopUse 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

WinHow
Brotli/gzip your assets5–10× smaller text payloads.
HTTP cachingLong max-age on hashed filenames.
Image formatsWebP / 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')]);

Test yourself

Q1. For independent async calls, prefer…
Q2. A high-resolution timer is provided by…
Q3. Biggest single performance win for most sites is usually…

Discussion

Loading…