Skip to content
Testing & QualityChapter 51 / 57Advanced5 min read

Performance: Measure First

Avoid premature optimization and find the real bottleneck with profiling, focusing on algorithms, data structures and N+1 queries before micro tricks.

On this page

1. What is this practice?

Performance work has three steps: measure, fix the biggest thing, measure again. Most of the gain comes from changing an algorithm, data structure or database query, not from small micro tricks.

2. Why does it matter?

Developers' guesses about "where is it slow" are often wrong. Optimization done by guessing makes the code harder to read and the real problem stays where it was.

Optimize by guessingMeasure first
Add memo wherever you are suspiciousThe profiler tells you where the time goes
Harder code, unknown gainBefore and after numbers in front of you
Micro tricks, like changing the loop styleChanging the algorithm or the query
A little bit everywhereThe biggest bottleneck first
A complex design from day oneSimple first, optimize when needed

3. When to follow it

LevelHow importantWhy
Learning projectWrite simple, readable code, do not optimizeCorrect first, fast later
Production codeWhen a user or a metric shows slowness, then measureTime goes where the gain is
Senior levelSet budgets and monitoring, like Core Web VitalsThe team sees the problem before users do

One thing at every level: do not write an obviously wrong algorithm from the start (like a lookup using a loop inside a loop). Measure first does not mean being careless.

4. Bad vs good code

Bad: lookup inside a loop

ts
function attachAuthors(posts: Post[], users: User[]) {
  return posts.map((post) => ({
    ...post,
    author: users.find((user) => user.id === post.authorId),
  }));
}

With 5,000 posts and 5,000 users, this is 25 million comparisons: O(n x m).

Good: the right data structure

ts
function attachAuthors(posts: Post[], users: User[]) {
  const usersById = new Map(users.map((user) => [user.id, user]));

  return posts.map((post) => ({
    ...post,
    author: usersById.get(post.authorId),
  }));
}

With a Map every lookup is O(1), and the total work is O(n + m).

Bad: N+1 query

ts
const posts = await db.post.findMany();
for (const post of posts) {
  post.author = await db.user.findUnique({ where: { id: post.authorId } });
}

Good: one query

ts
const posts = await db.post.findMany({ include: { author: true } });

How to measure first?

ts
const start = performance.now();
const result = attachAuthors(posts, users);
console.log(`attachAuthors: ${(performance.now() - start).toFixed(1)}ms`);
bash
EXPLAIN ANALYZE SELECT * FROM posts WHERE author_id = 42;

What is the difference?

ThingBadGood
LookupArray.find in a loopA Map built once
DatabaseA separate query for every rowOne query with a join
DecisionA guessA number

5. How to apply it

How to fix performance
Write the problem as a number (page 4s, API 2s)
Profile: browser, React Profiler, server timing, EXPLAIN
Pick the biggest bottleneck
Change the algorithm, query or data structure
Measure again
If there is no gain, revert the change
Where it is slowTool
Page loadLighthouse, Core Web Vitals, Network tab
React renderReact DevTools Profiler
JavaScriptBrowser Performance tab, performance.now()
DatabaseEXPLAIN ANALYZE, slow query log
ServerRequest timing logs

Take care of resources too: pool database connections, close files and streams, and clear timers and listeners when the work is done. A leak is a performance bug as well.

6. Exceptions and common mistakes

When the rule does not apply: when the design itself depends on scale (like an index on a table with millions of rows, or a known O(n x n) algorithm on a hot path), make the right choice up front. That is not premature optimization, it is basic engineering.

Mistake: useMemo and React.memo on every component

Why? Every memo has its own cost and makes the code harder to read, and the gain is often zero.

Better: Catch the slow render with the Profiler and add memo only there, or fix the component structure.

Mistake: Micro optimization, like for loop vs map

Why? The real time goes into the network and the database, not the loop style.

Better: Look at the network and queries first, then the algorithm.

Mistake: Optimizing and not measuring again

Why? You cannot tell whether the change helped or hurt.

Better: Write the before and after numbers in the PR description.

7. What to learn before and after

Final quick revision

CheckYes?
Problem written as a number
Bottleneck found with a profiler
Algorithm or query first, micro tricks later
Measured again after the change
Change reverted if there was no gain