var string = "abe123";
var string = "abe123";
let isLastNameValid = false;
const THREE_DIGIT_REGEXP = /\d{3,}/;
isLastNameValid = THREE_DIGIT_REGEXP.test(string);
let isLastNameValid = false;
let digits = 0;
for(let i = 0; i < string.length; i++) {
!isNaN(string.charAt(i)) && digits++;
}
isLastNameValid = digits >= 3;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Regex | |
Loop |
Test name | Executions per second |
---|---|
Regex | 10804066.0 Ops/sec |
Loop | 600001.6 Ops/sec |
Let's dive into the world of MeasureThat.net and explore what's being tested in this benchmark.
Benchmark Definition
The benchmark is designed to test two approaches for validating three-digit strings: using regular expressions (Regex) and looping through each character.
Script Preparation Code
Both test cases start with the same preparation code:
var string = "abe123";
This sets a predefined input string string
that will be used as the test subject for both approaches.
Benchmark Definition Details
Now, let's analyze the two benchmark definitions:
string
are digits:let isLastNameValid = false;
const THREE_DIGIT_REGEXP = /\\d{3,}/;
isLastNameValid = THREE_DIGIT_REGEXP.test(string);
This approach relies on a predefined regular expression pattern (\\d{3,}
) to match three or more consecutive digits at the end of the string.
Pros and Cons
Advantages:
Disadvantages:
string
and count the digits:let isLastNameValid = false;
let digits = 0;
for (let i = 0; i < string.length; i++) {
!isNaN(string.charAt(i)) && digits++;
}
isLastNameValid = digits >= 3;
This approach involves a simple loop that checks each character of the string
using the isNaN()
function to detect numeric characters.
Pros and Cons
Advantages:
Disadvantages:
Library: THREE_DIGIT_REGEXP
The THREE_DIGIT_REGEXP
variable is a predefined regular expression pattern that is used in the Regex benchmark. This pattern is likely defined by MeasureThat.net to provide a consistent and efficient way to match three or more consecutive digits at the end of a string.
Special JavaScript Feature/Syntax: None
There are no special JavaScript features or syntax used in these benchmark definitions.
Other Alternatives
If you were to rewrite this benchmark, you could consider alternative approaches, such as:
\\d{3}(?:[0-9]*[0-9])?
)Keep in mind that these alternatives might affect performance or accuracy, so it's essential to test and validate them thoroughly.