Map vs Array.findIndex

Map vs findIndex demo

Same comment list: each row looks up the author by id. Toggle between Array + findIndex and Map to use a different lookup. Add comments to increase lookups per render. Then run the benchmark below (in a Web Worker) to see the difference at scale.

Array + findIndex (O(n) per lookup)
const index = users.findIndex(u => u.id === id)
return index === -1 ? undefined : users[index]
Map (O(1) per lookup)
const usersById = new Map(users.map(u => [u.id, u]))
return usersById.get(id)

Live: comments with author lookup

Each row does one lookup by authorId. Current: findIndex — 6 lookups per render.

  • Great post! — Alice (admin)
  • I prefer Map for lookups. — Bob (user)
  • findIndex is fine for small lists. — Carol (editor)
  • We use both: array for order, Map for get-by-id. — Alice (admin)
  • O(1) vs O(n) matters at scale. — Dave (user)
  • Nice benchmark below. — Eve (editor)

Benchmark

How many items to create and how many random lookups to run. Runs in a Web Worker so the UI stays responsive. Map is typically much faster for large lists and many lookups.