String startsWith vs regex

Benchmark created on


Description

Tests /^prefix/.test() vs String.startsWith("prefix")

Setup

const getRandomPart = () => Math.random().toString(36).substring(2, 8);
const getRandomLength = () => Math.floor(Math.random() * 4) + 2; // 2 to 5 parts

const strings = Array.from({ length: 100 }, (_, i) => {
  const parts = Array.from({ length: getRandomLength() }, getRandomPart);
  let str = parts.join('.');
  if (Math.random() < 0.3) { // ~30% start with prefix!
    str = 'prefix!' + str;
  }
  return str;
});

Test runner

Ready to run.

Testing in
TestOps/sec
Regex match
const regex = /^prefix!/;
for (let str of strings) {
   str.match(regex)
}
ready
Regex test
const regex = /^prefix!/;
for (let str of strings) {
	regex.test(str);
}
ready
String.startsWith
const prefix = 'prefix!';
for (let str of strings) {
	str.startsWith(prefix);
}
ready

Revisions

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