var foo = ['+++', '---', '===', '@@@', null, undefined, '', 'foo'];
var test = [];
for (var i = 0; i < 1000; i++) {
test = [test, foo];
}
test.map((x) => /^\+\-\=\@/.test(x) ? "'" + x : x);
test.map((x) => {
if (
x?.startsWith('+') ||
x?.startsWith('-') ||
x?.startsWith('=') ||
x?.startsWith('@')
) {
return "'" + x;
}
return x;
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
regex | |
startWith |
Test name | Executions per second |
---|---|
regex | 6216.2 Ops/sec |
startWith | 7478.9 Ops/sec |
Let's dive into the explanation of the provided benchmark.
What is being tested?
The benchmark measures the performance difference between two approaches to check if a string starts with a specific character or substring: regular expressions (regex
) and the startsWith
method (also known as "string matching" or "substring checking").
In this specific test, both methods are applied to an array of strings foo
, which contains a mix of strings with different characters, including some null and undefined values. The benchmark is run 1000 times for each string in the array.
Options compared
The two options being compared are:
regex
): This approach uses a regular expression to check if a string starts with a specific character or substring. In this case, the regular expression ^\\+\\-\\=\\@/
matches any string that starts with one of these characters.startsWith
method: This is a built-in JavaScript method that checks if a string starts with a specified value.Pros and Cons
Here's a brief summary of the pros and cons of each approach:
regex
):startsWith
for certain use cases.startsWith
for simple string matching, may have performance implications due to the overhead of compiling regular expressions.startsWith
method:Library used
In this benchmark, no external library is explicitly mentioned. However, the test.map()
function is used to apply the testing logic to each element in the array foo
. This suggests that the benchmark is using built-in JavaScript functionality.
Special JS feature or syntax
There's a subtle point worth mentioning: the use of the optional chaining operator (?.
) in the startsWith
method implementation. This operator is only available in ECMAScript 2020 and later versions of JavaScript. In earlier versions, you would need to use explicit null checks instead.
Other alternatives
If you wanted to test other approaches to string matching or substring checking, some possible alternatives could include:
includes()
or slice()
.