Replacement

Benchmark created on


Setup

const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';

// Global flag required when calling replaceAll with regex
const regex = / ([^ ]*) /ig;
function replacer(match) {
  return "[" + "a".repeat(match.length - 2) + "]";
};
let a = p;
let b = p;
let c = p;
let d = p;
let e = p;
let f = p;
let g = p;
let dArray = p.split('');

Test runner

Ready to run.

Testing in
TestOps/sec
replaceAll
//let a = p;
a = p.replaceAll(regex, replacer);
ready
Exec loop
//let b = p;
while ((match = regex.exec(b)) != null) {
  b = b.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + b.slice(regex.lastIndex);
}
ready
replace
//let c = p;
c = p.replace(regex, (match) => { return "[" + "a".repeat(match.length - 2) + "]"});
ready
array
//let dArray = p.split('');
while ((match = regex.exec(d)) != null) {
  dArray.fill('a', match.index + 1, regex.lastIndex - 1);
  dArray[match.index] = '[';
  dArray[regex.lastIndex - 1] = ']';
}
d = dArray.join('');
ready
template literals
while ((match = regex.exec(e)) != null) {
  e = `${e.slice(0, match.index)}[${'a'.repeat(match[0].length - 2)}]${e.slice(regex.lastIndex)}`;
}
ready
stringbuilder
while ((match = regex.exec(f)) != null) {
  let sb = [];
  sb.push(f.slice(0, match.index));
  //sb.push('[');
  sb.push('[' + 'a'.repeat(match[0].length - 2) + ']');
  //sb.push(']');
  sb.push(f.slice(regex.lastIndex));
  f = sb.join('');
}
ready
stringbuilder2
while ((match = regex.exec(g)) != null) {
  let sb = [];
  sb.push(g.slice(0, match.index));
  sb.push('[');
  for(let i = 0 ; i < match[0].length - 2; i++) {
    sb.push('a');
  }
  sb.push(']');
  sb.push(g.slice(regex.lastIndex));
  g = sb.join('');
}
ready

Revisions

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