DEV Community

Cover image for This JavaScript Line Took 10 Seconds: Big-O Explained With a Real Bug
Muiduzzaman Lipu for Refactorly

Posted on

This JavaScript Line Took 10 Seconds: Big-O Explained With a Real Bug

This line of JavaScript took 10.7 seconds:

const result = orders.map(order => ({
  ...order,
  user: users.find(u => u.id === order.userId),
}));
Enter fullscreen mode Exit fullscreen mode

The fixed version takes 26 milliseconds, with the same data and the same result. The difference is Big-O, and it's much easier to understand from real numbers than from a textbook. All timings below are from Node.js 22 on an Apple M4, best of 3 runs.

Video version:

The numbers

orders and users both have n items:

n find() inside map()
10,000 27 ms
100,000 2,666 ms
200,000 10,709 ms

10× more data made it ~100× slower. 2× more data made it ~4× slower. With a hundred test users it's instant, so you won't notice in development.

Why: a scan inside a loop is O(n²)

  • orders.map(...) runs n times.
  • Each time, users.find(...) scans the array from the start until it finds a match: up to n steps.

Total work ≈ n × n = O(n²). For n = 200,000 that's up to 40 billion comparisons. That's what "quadratic" means in practice: the time grows with the square of the input.

The fix: build a Map once

const byId = new Map(users.map(u => [u.id, u]));   // one pass: O(n)

const result = orders.map(order => ({
  ...order,
  user: byId.get(order.userId),                     // direct lookup: O(1)
}));
Enter fullscreen mode Exit fullscreen mode

Building the map is one pass over the users. After that, byId.get() jumps straight to the right entry instead of scanning. Total: O(n). 200,000 orders: 26 ms, about 400× faster.

The same bug in disguise

find, includes and indexOf all scan the array. Inside a loop, each one is O(n²). Measured at n = 100,000:

// 532 ms
users.filter(u => !banned.includes(u.id));

// 4 ms
const bannedSet = new Set(banned);
users.filter(u => !bannedSet.has(u.id));
Enter fullscreen mode Exit fullscreen mode
// 354 ms: the classic "remove duplicates" snippet
ids.filter((x, i) => ids.indexOf(x) === i);

// 2 ms (and it keeps first-seen order)
[...new Set(ids)];
Enter fullscreen mode Exit fullscreen mode

Cheat sheet

  • find, includes, indexOf, some: O(n), they scan.
  • Map.get, Map.has, Set.has: O(1) on average, direct lookup.
  • A scan inside a loop (map, filter, forEach, for) = O(n²).
  • O(n²): 10× the data → 100× the time.
  • Build the Map or Set once, outside the loop.
  • Test with realistic data sizes, not 100 rows.

Go search your codebase for .find( inside .map(. How many did you find? 👇


I post one tested coding tip every day on YouTube at Refactorly. The 30-second version of this one is here.

Top comments (0)