String replacement methods (v2)

Revision 2 of this benchmark created on


Setup

const ROMAN_NUMERALS = `Ⅰ Ⅱ Ⅲ Ⅹ`
const BUFFER = 1_000_000;
const longstring = 'a'.repeat(BUFFER) + ROMAN_NUMERALS;
let str = '';

Teardown

document.body.innerHTML = str.slice(BUFFER);

Test runner

Ready to run.

Testing in
TestOps/sec
mapper
const mapper = new Map([
  ['Ⅰ', '1'],
  ['Ⅱ', '2'],
  ['Ⅲ', '3'],
  ['Ⅹ', '10']
])

str = Array.from(longstring).map(x => mapper.get(x) ?? x).join('')
ready
iterate
for (let char of longstring) {
  let code = char.charCodeAt(0);
  if (code >= 0x2160 && code < 0x216d) {
    str += code - 0x2160;
  } else {
    str += char;
  }
}
ready
regex with replace function
str = longstring.replace(/[\u2160-\u216b]/g, chr => String(chr.charCodeAt(0) - 0x215f));
ready
many regexes
str = longstring.replace(/\u2160/g, '1');
str = str.replace(/\u2161/g, '2');
str = str.replace(/\u2162/g, '3');
str = str.replace(/\u2169/g, '10');
ready
mapper with replaceAll
const mapper = new Map([
  ['Ⅰ', '1'],
  ['Ⅱ', '2'],
  ['Ⅲ', '3'],
  ['Ⅹ', '10']
])

str = longstring;
mapper.forEach((val, key) => {
	str = str.replaceAll(key, val);
});
ready

Revisions

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