Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Removes regex from extended length path check #26

Merged

Conversation

emagers
Copy link
Contributor

@emagers emagers commented May 8, 2023

The existing method uses regex to check if the first four characters indicate that the path is an extended-length path. This is not as performant as using startsWith which checks the first four characters without using a regex.

Using the benchmark package, I compared the performance by evaluating the following strings:

const NORMAL_STRING_WITH_REPLACE = "C:\\test\\path";
const EXTENDED_PATH = "\\\\?\\C:\\test\\path";
const NORMAL_STRING_NO_REPLACE = "C:/test/path";

function slash_original(path) {
	const isExtendedLengthPath = /^\\\\\?\\/.test(path);

	if (isExtendedLengthPath) {
		return path;
	}

	return path.replace(/\\/g, '/');
}

function slash_new(path) {
	const isExtendedLengthPath = path.startsWith("\\\\?\\");

	if (isExtendedLengthPath) {
		return path;
	}

	return path.replace(/\\/g, '/');
}

The resulting data backed up the idea for performance improvement:

NORMAL_STRING_WITH_REPLACE

original x 4,243,922 ops/sec ±0.95% (88 runs sampled)
new x 4,591,650 ops/sec ±0.78% (91 runs sampled)

~8.1% increase in ops/sec

EXTENDED_PATH

original x 26,703,612 ops/sec ±1.16% (93 runs sampled)
new x 43,472,723 ops/sec ±3.22% (87 runs sampled)

~62% increase in ops/sec

NORMAL_STRING_NO_REPLACE

original x 10,698,194 ops/sec ±0.82% (92 runs sampled)
new x 12,566,525 ops/sec ±0.80% (94 runs sampled)

~17% increase in ops/sec

Note that these benchmarks were run on my local notebook though repeated multiple times with similar results.

index.js Outdated Show resolved Hide resolved
@sindresorhus sindresorhus merged commit 03cce86 into sindresorhus:main May 9, 2023
@emagers emagers deleted the startsWith_rather_than_regex branch May 9, 2023 19:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants