Regex Replace Benmark (v2)

Revision 2 of this benchmark created on


Setup

const testStr = "Hello <world> & \"quotes\" \u2028 new line \u2029 done.".repeat(10000);

const forbiddenChars = {
  '<': '\\u003C',
  '>': '\\u003E',
  '"': '\\u0022',
  '&': '\\u0026',
  '\u2028': '\\u2028',
  '\u2029': '\\u2029',
};

const forbiddenRe = /[<>&"\u2028\u2029]/g;

// --- Variant 1: Regex with external function
function replaceForbidden(c) {
  return forbiddenChars[c];
}
function escape_regex_func(str) {
  return str.replace(forbiddenRe, replaceForbidden);
}

// --- Variant 2: Regex inline
function escape_regex_inline(str) {
  return str.replace(forbiddenRe, c => forbiddenChars[c]);
}

// --- Variant 3: Loop + string concat
function escape_loop_concat(str) {
  let out = '';
  for (let i = 0; i < str.length; i++) {
    const c = str[i];
    out += forbiddenChars[c] ?? c;
  }
  return out;
}

// ---  Variant 4: Loop + array join
function escape_loop_join(str) {
  const out = [];
  for (let i = 0; i < str.length; i++) {
    const c = str[i];
    out.push(forbiddenChars[c] ?? c);
  }
  return out.join('');
}

// --- Variant 5: Regex.test + Regex replace
function escapeForbidden(str) {
  str = String(str);
  return forbiddenRe.test(str) 
    ? str.replace(forbiddenRe, (c) => forbiddenChars[c])
    : str;
}

Test runner

Ready to run.

Testing in
TestOps/sec
Variant 1: Regex with external function
escape_regex_func(testStr);
ready
Variant 2: Regex inline
escape_regex_inline(testStr);
ready
Variant 3: Loop + string concat
escape_loop_concat(testStr);
ready
Variant 4: Loop + array join
escape_loop_join(testStr);
ready
Variant 5: Regex.test + Regex replace
escapeForbidden(testStr);
ready

Revisions

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