const testStrFirst = 'foo';
['foo', 'bar'].includes(testStrFirst);
const testStrSecond = 'bar';
['foo', 'bar'].includes(testStrSecond);
const testStrNotMatch = 'baz';
['foo', 'bar'].includes(testStrNotMatch);
const testStrFirst = 'foo';
testStrFirst.match(/^(foo|bar)$/);
const testStrSecond = 'bar';
testStrSecond.match(/^(foo|bar)$/);
const testStrNotMatch = 'baz';
testStrNotMatch.match(/^(foo|bar)$/);
const testStrFirst = 'foo';
if (testStrFirst == 'foo' || testStrFirst == 'bar') {}
const testStrSecond = 'bar';
if (testStrFirst == 'foo' || testStrFirst == 'bar') {}
const testStrNotMatch = 'baz';
if (testStrFirst == 'foo' || testStrFirst == 'bar') {}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.includes | |
String.match | |
Multiple if Conditions |
Test name | Executions per second |
---|---|
Array.includes | 76279400.0 Ops/sec |
String.match | 15121363.0 Ops/sec |
Multiple if Conditions | 187776576.0 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares three approaches to check if a string matches multiple possibilities:
Array.includes
String.match
with regular expressionsif
conditions using equality checks (==
)Options Compared
includes()
function to search for an element in an array. It returns true
if the element is found and false
otherwise./^(foo|bar)/
pattern matches any string that starts with either "foo" or "bar".==
) to compare the input string with multiple possibilities.Pros and Cons
Array.includes
due to the overhead of compiling the regex pattern.Library and Special JS Features
includes()
method is a built-in JavaScript function.String.match
approach. If you're not familiar with regex, it's worth learning about them for more complex matching tasks.Other Alternatives
If you need to perform string matching with regular expressions, consider using other libraries like regex-escape
or regex-test
. For simple string matching, you could also use a dedicated library like string-match
.
Benchmark Considerations
When choosing an approach, consider the following factors:
Array.includes
might be the best choice. However, if flexibility and accuracy are more important, String.match
with regular expressions could be the better option.if
conditions might be easier to understand than regular expressions or built-in functions like includes()
.String.match
with regular expressions is a good choice.