Split on first deliminator (v7)

Revision 7 of this benchmark created on


Description

Test the performance of splitting a string only on the first delimitor

Setup

function test_single(path, split) {
	
	let component, last;
	
	while (path[0] === '/') path = path.slice(1);
	
	for (;;) {
		
		last = path;
		
		[component, path] = split(path);
		
		if (!path) break;
	}
}

const test_paths = [
	'/home/test/src/project/deps/libsomething/dist/file.js',
	'//net/path/with/oops///slashes'
];

function test(split) {
	for (const p of test_paths) test_single(p, split);
}

Test runner

Ready to run.

Testing in
TestOps/sec
Regex with lastIndex
const RE_FIRST = /([^/]*)\/*/y;

function split(path) {
  RE_FIRST.lastIndex = 0;
  const match = RE_FIRST.exec(path);
  const tail = path.slice(RE_FIRST.lastIndex);
  return [match[1], tail];
}

test(split);
ready
IndexOf, charCodeAt
function split(p) {
 	const i = p.indexOf('/');
 	if (i === -1) return [p, ''];
 	let j = i + 1;
 	// consume all slashes after the first one
 	while (p.charCodeAt(j) === 47) j++;
 	return [p.slice(0, i), p.slice(j)];
}

test(split);
ready
Regex with indexes
const pattern = /^\/*([^\/]*)\/*(.*)$/;

function split(p) {
	const match = pattern.exec(p);
	return [match[1], match[2]]
}

test(split);
ready
IndexOf, strings
function split(p) {
 	const i = p.indexOf('/');
 	if (i === -1) return [p, ''];
 	let j = i + 1;
 	// consume all slashes after the first one
 	while (p[j] === '/') j++;
 	return [p.slice(0, i), p.slice(j)];
}

test(split);
ready

Revisions

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