Replace multiple values - single RegExp vs loop

Benchmark created on


Setup

const strings = [...Array(100)].map(() => 'abc '.repeat(Math.random() * 30 | 0) + [...Array(1000)].map(() => `{${Math.random() * 100 | 0}}`).join('') + 'def'.repeat(Math.random() * 30 | 0));
const values = Object.fromEntries([...Array(60)].map((_, i) => [2 * i, (Math.random() * 1000 | 0).toString()]));

const escapeRegExpChars = (s) => s.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&');

function a(str, replacements) {
	const regex = new RegExp(`{(${Object.keys(replacements).map(escapeRegExpChars).join('|')})}`, 'g');
	return str.replace(regex, (_, key) => replacements[key] || '');
}

function b(str, replacements) {
	return str.replace(/{([^} ]+)}/g, (full, val) => val in replacements ? replacements[val] : full);
}

function c(str, replacements) {
	return Object.entries(replacements).reduce((str, [key, value]) => str.replaceAll(`{${key}}`, value), str);
}

Test runner

Ready to run.

Testing in
TestOps/sec
big regexp
let result = strings.map(s => a(s, values));
ready
check all brackets
let result = strings.map(s => b(s, values));
ready
multiple replace
let result = strings.map(s => c(s, values));
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.