const testStrFirst = 'http://www.google.com';
testStrFirst.includes("localhost") && testStrFirst.includes("https")
const testStrFirst = 'http://www.google.com';
testStrFirst.match(/(https|localhost)/);
const testStrFirst = 'http://www.google.com';
testStrFirst.match(/https/) && testStrFirst.match(/localhost/);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
String.includes | |
Single Match | |
Multiple Match |
Test name | Executions per second |
---|---|
String.includes | 34278144.0 Ops/sec |
Single Match | 17993906.0 Ops/sec |
Multiple Match | 16417613.0 Ops/sec |
Overview of the Benchmark
The provided benchmark compares three approaches for matching a string against multiple possibilities: String.includes
, String.match
with a single regular expression, and String.match
with multiple regular expressions.
Approach 1: String.includes
This approach checks if the string contains the specified substring. The includes
method is called twice on the same string, which may lead to unnecessary work if there's no match in between. On the other hand, it can be faster if the search space is large and the search is not sequential.
Pros:
Cons:
Approach 2: Single Match with String.match
This approach uses a single regular expression to match against multiple substrings. The match
method returns an array of matches, and the test code checks for any non-empty matches.
Pros:
includes
Cons:
Approach 3: Multiple Matches with String.match
This approach uses multiple regular expressions to match against separate substrings. The test code checks for each non-empty match individually.
Pros:
Cons:
Library Used: None
There are no libraries explicitly mentioned in the benchmark definition or test cases. However, JavaScript's built-in String
methods (includes
, match
) are used.
Special JS Features/Syntax: None
There are no special JavaScript features or syntax used in this benchmark.
Alternatives
Other alternatives for matching strings against multiple possibilities include:
Keep in mind that the choice of approach depends on the specific requirements and constraints of your use case.