const tests = [
'Alasdkfjdsfndv dfjwsdfsmd +\
s@sdfsdvdsv dwoaslkvkl +\
skcslmvklfnkl klaml fm +\
wemvfz;lpakpokqmdsfdkm +\
kreklmswlms lmfklsmskl +\
l;fl; s,dl;fmsklnkfsd; +\
sahfwijrn 1',
'3Jognsahasdojjjdishuihjnj +\
sdfskdfkshfskmfsdjnf',
'Asnasbdbasdahsfsdjfsdfbds +\
eiejdksjhsjj7'
]
function strContainsNumsv1(str) {
return str.split('').findIndex(e => [0,1,2,3,4,5,6,7,8,9].includes(+e)) != -1;
}
function strContainsNumsv2(str) {
return /\d/.test(str);
}
function strContainsNumsv3(str) {
return /^(?=.*[0-9]).*$/.test(str);
}
function runTestv1() {
tests.forEach(e => strContainsNumsv1(e))
}
function runTestv2() {
tests.forEach(e => strContainsNumsv2(e))
}
function runTestv3() {
tests.forEach(e => strContainsNumsv3(e))
}
runTestv1()
runTestv2()
runTestv3()
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Find a number within a string via string and array methods | |
Find a number within a string via literal regexp | |
Find a number within a string via strong literal regexp |
Test name | Executions per second |
---|---|
Find a number within a string via string and array methods | 337716.2 Ops/sec |
Find a number within a string via literal regexp | 1255559.8 Ops/sec |
Find a number within a string via strong literal regexp | 734599.6 Ops/sec |
Let's dive into the benchmark.
Benchmark Overview
The provided JSON represents a JavaScript microbenchmark that compares three approaches to search for a digit (number) within a given string:
split()
and findIndex()
./\\d/
./^(?=.*[0-9]).*$/
.Approaches Compared
The benchmark compares the execution time of each approach for a set of test cases.
strContainsNumsv1
): Splits the input string into an array of characters, then uses findIndex()
to find the index of the first character that is a digit.strContainsNumsv2
): Uses the /\\d/
pattern to match any single digit within the input string. The test()
method returns a boolean indicating whether the entire string matches this pattern.strContainsNumsv3
): Uses the /^(?=.*[0-9]).*$/
pattern, which is more restrictive than the previous one, ensuring that the string contains at least one digit. The test()
method returns a boolean indicating whether the entire string matches this pattern.Pros and Cons
Here's a brief overview of each approach:
strContainsNumsv2
): Pros: concise, easy to write, and relatively fast. Cons: may not match all edge cases (e.g., non-ASCII digits).strContainsNumsv3
): Pros: more robust than the previous approach, ensures that the string contains at least one digit. Cons: more complex pattern, potentially slower due to the additional overhead.Library and Special JS Features
There are no notable libraries or special JavaScript features used in this benchmark.
Other Considerations
When choosing between these approaches, consider the trade-off between performance, code readability, and robustness:
strContainsNumsv2
).strContainsNumsv3
).strContainsNumsv1
).