Skip to content
jshacks.dev
Performance

Avoid re-creating objects in hot loops

Move constant regexes, formatters and lookup tables out of a loop that runs millions of times, so they are created once instead of on every iteration.

1 min read
Summarize in AI

Creating the same object on every iteration of a hot loop produces garbage and repeats work. Anything that does not change belongs outside it.

loop.jsJavaScript
const lines = ['id=1', 'id=22', 'id=333'];

// Slow: a new regex and a new Set on each iteration.
for (const line of lines) {
  const re = /id=(\d+)/;
  const allowed = new Set(['1', '22']);
  const id = re.exec(line)[1];
  if (allowed.has(id)) console.log('kept', id);
}

// Better: created once, used many times.
const re = /id=(\d+)/;
const allowed = new Set(['1', '22']);
for (const line of lines) {
  const id = re.exec(line)[1];
  if (allowed.has(id)) console.log('kept', id);
}
Text
kept 1
kept 22
kept 1
kept 22

The first loop prints the first two lines and the second loop the same two, so both give the same result. A regex literal inside a loop creates a new RegExp object each time the expression is evaluated, and the Set is rebuilt from an array on every pass.

Engines can sometimes hoist or cache constant literals, so a micro-benchmark may show little difference; the gain is largest for Intl formatters and big lookup tables. Do not share a regex with the g or y flag across calls without resetting lastIndex, because it keeps state between calls. See RegExp lastIndex.

Taggednode 24
Share

More snippets

Performance

Time code with performance.now

Time a block of code with performance.now, which returns a monotonic high-resolution timestamp in milliseconds, and avoid the clock jumps Date.now can have.

1 min read
Performance

Reduce JSON size by removing nulls

Drop null and undefined fields from an API payload with a JSON.stringify replacer, shrinking responses, and check clients treat a missing key like null.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.