Efficient Code

Choose the Right Data Structure

Example

Looking something up in an array is O(n); in a Set or Map it is O(1) on average:

const ids = Array.from({ length: 50_000 }, (_, i) => i);
const idSet = new Set(ids);
const wanted = Array.from({ length: 2_000 }, (_, i) => i * 25);

let t = performance.now();
let found1 = wanted.filter((w) => ids.includes(w)).length;
const arrayMs = performance.now() - t;

t = performance.now();
let found2 = wanted.filter((w) => idSet.has(w)).length;
const setMs = performance.now() - t;

console.log("same result:", found1 === found2);
console.log("Set lookup is faster:", setMs < arrayMs);

Output

same result: true
Set lookup is faster: true

Load Less JavaScript

  1. Split code: load routes and heavy features with dynamic import().
  2. Remove unused dependencies; check bundle size (e.g. with a bundle analyzer).
  3. Use defer for scripts; avoid render-blocking JavaScript.
  4. Cache API responses and memoise expensive pure functions.
  5. Move CPU-heavy work to Web Workers.