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.
Creating the same object on every iteration of a hot loop produces garbage and repeats work. Anything that does not change belongs outside it.
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);
}kept 1
kept 22
kept 1
kept 22The 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.