var string = "isAlphaNumeric091,";
var string = "isAlphaNumeric091,";
/^[a-z0-9]+$/i.test(string)
function isAlphaNumeric(str) {
for (let i = 0; i < str.length; i++) {
let code = str.charCodeAt(i)
if (!(code > 47 && code < 58) && // numeric (0-9)
!(code > 64 && code < 91) && // upper alpha (A-Z)
!(code > 96 && code < 123)) { // lower alpha (a-z)
return false
}
}
return true
}
isAlphaNumeric(string)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Regex | |
charCodeAt |
Test name | Executions per second |
---|---|
Regex | 5713485.0 Ops/sec |
charCodeAt | 5159164.5 Ops/sec |
Let's break down the provided JSON data and explain what is being tested, compared, and their pros and cons.
Benchmark Definition
The benchmark definition specifies two test cases:
regex
: This test case uses a regular expression to check if a string contains only alphanumeric characters (letters and numbers). The regular expression /^[a-z0-9]+$/i.test(string)
checks the input string string
for matches against this pattern.charCodeAt
: This test case manually checks each character in the input string using the charCodeAt()
method to get the ASCII code of each character. It then checks if the code falls within the range of alphanumeric characters (47-57 for numbers, 64-90 for uppercase letters, and 96-122 for lowercase letters). If any character does not meet this condition, it returns false
. Otherwise, it returns true
.Comparison Options
The two test cases are compared to measure which approach is faster:
charCodeAt()
method.Pros and Cons
Here are some pros and cons of each approach:
Regex
Pros:
Cons:
charCodeAt
Pros:
Cons:
Library Used
The charCodeAt()
test case uses the built-in JavaScript method charCodeAt()
, which is a part of the ECMAScript standard.
Special JS Feature/Syntax
There are no special JavaScript features or syntax used in this benchmark, other than regular expressions. The use of i
at the end of the regex pattern /^[a-z0-9]+$/i
makes it case-insensitive.
Other Alternatives
If you wanted to test alternative approaches, some possible options could be:
grep
, sed
) for regex checks