Regex vs endsWith

Benchmark created on


Setup

const sites = [
  // Music services
  { key: 'allmusic', regex: /allmusic\.com$/i, domain: 'allmusic.com' },
  { key: 'discogs', regex: /discogs\.com$/i, domain: 'discogs.com' },
  // Streaming platforms
  { key: 'spotify', regex: /spotify\.com$/i, domain: 'spotify.com' },
  { key: 'soundcloud', regex: /soundcloud\.com$/i, domain: 'soundcloud.com' },
  { key: 'apple', regex: /music\.apple\.com$/i, domain: 'music.apple.com' },
  { key: 'youtube', regex: /youtube\.com$/i, domain: 'youtube.com' },
  // Social media
  { key: 'twitter', regex: /twitter\.com$/i, domain: 'twitter.com' },
  { key: 'tiktok', regex: /tiktok\.com$/i, domain: 'tiktok.com' },
  { key: 'facebook', regex: /facebook\.com$/i, domain: 'facebook.com' },
  { key: 'instagram', regex: /instagram\.com$/i, domain: 'instagram.com' },
];
const domains = sites.flatMap(({ domain }, index) => [
  domain,
  `sub.${domain}`,
  `sub2.${domain}`,
  `sub3.${domain}`,
  `domain${index}.com`,
  `otherdomain${index}.com`,
  `fakedomain${index}.com`
]);

Test runner

Ready to run.

Testing in
TestOps/sec
regex
let keys = domains.map((domain) => {
	return sites.find((site) => site.regex.test(domain))?.key || 'other';
})
ready
endsWith
let keys = domains.map((domain) => {
	return sites.find((site) => domain.endsWith(site.domain))?.key || 'other';
})
ready

Revisions

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