String replace vs regex replace

Benchmark created on


Setup

function generateLongString(word, repetitions) {
  let longString = "";
  for (let i = 0; i < repetitions; i++) {
    longString += word + " "; // Concatenate the word and a whitespace
  }
  return longString.trim(); // Remove the trailing whitespace
}

Test runner

Ready to run.

Testing in
TestOps/sec
While Loop
let longString = generateLongString("word", 1000);

while(longString.includes(' ')) {
	longString = longString.replace(' ', '_');
}
ready
Regex
let longString = generateLongString("word", 1000);

longString = longString.replace(/\s/g, '_');
ready

Revisions

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