Regexp vs slice (v2)

Revision 2 of this benchmark created on


Setup

const randFrom = (arr) => arr[Math.floor((Math.random()*arr.length))];


const idregex = /^(?<type>investigation|surface|shared):(?<id>.*)$/

const prefixes = ["investigation:", "surface:", "shared:", "something:", "else:"]
const strings = Array(10000).fill().map((x, i) => `${randFrom(prefixes)}test${i}`)

let hits = 0

Teardown

console.log(hits)

Test runner

Ready to run.

Testing in
TestOps/sec
Regex
const str = randFrom(strings)

const match = str.match(idregex)
if (match) {
	const type = match?.groups.type
	const id = match?.groups.id
	
	if (type === 'investigation') {
		hits += 1
	} else if (type === 'shared') {
		hits += 1		
	} else if (type === 'surface') {
		hits += 1	
	}
}

ready
Direct
const str = randFrom(strings)

if (str.startsWith('investigations:')) {
	const id = str.slice('investigations:'.length)
	hits += 1
} else if (str.startsWith('shared:')) {
	const id = str.slice('shared:'.length)
	hits += 1
} else if (str.startsWith('surface:')) {
	const id = str.slice('surface:'.length)
	hits += 1
}

ready

Revisions

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