I have some code that does 4500 string replacement operations.
I measure how long this code takes to execute using performance.now()
before and after.
Sometimes it takes 20-30 ms to execute, and sometimes it takes 1550-1600 ms.
I cannot figure out why the performance can be so random. Is it some sort of CPU branch prediction failures or Node.js optimizations that somehow cache the replacement results?
// example `row`:
// row = { pattern: '/some words/', replacement: 'some other words' }
for (const row of replacements) {
// Avoid replacing with the word "undefined":
if (!row.replacement) { row.replacement = ''; }
const regex = new RegExp(row.pattern, 'gi');
modifiedText = modifiedText.replace(regex, row.replacement);
}