['apple', 'orange', 'lemon', 'blueberry'].includes('lemon')
['apple', 'orange', 'lemon', 'blueberry'].indexOf('lemon') > -1
/^(apple|orange|lemon|blueberry)$/.test('lemon')
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
includes() | |
indexOf() | |
test() |
Test name | Executions per second |
---|---|
includes() | 1038918720.0 Ops/sec |
indexOf() | 186253104.0 Ops/sec |
test() | 44778180.0 Ops/sec |
Let's break down the provided JSON and benchmark preparation code to understand what's being tested.
Benchmark Definition
The benchmark is defined as three test cases that compare the performance of different string methods: includes()
, indexOf()
, and test()
.
Options Compared
includes()
: The includes()
method checks if a specified value (in this case, 'lemon') is present in an array or string.indexOf()
: The indexOf()
method finds the index of the first occurrence of a specified value (in this case, 'lemon') in an array or string. If not found, it returns -1.test()
: The test()
method is a part of the regular expression API and checks if a string matches a given pattern.Pros and Cons
includes()
:indexOf()
: includes()
.test()
:Library Used
In this benchmark, the includes()
method is a built-in JavaScript method that doesn't rely on any external library. The indexOf()
method also comes with JavaScript. However, test()
uses a library (the RegExp
object) for regular expressions.
Special JS Feature/Syntax
There's no special feature or syntax in this benchmark besides the use of regular expressions and built-in string methods.
Other Alternatives
In addition to the provided methods, you could compare other approaches such as:
slice()
or subarray()
: Extracting a subset of an array or creating a new array with a specific index range.Here's an example for the first test case:
const arr = ['apple', 'orange', 'lemon', 'blueberry'];
console.log(arr[2]); // Output: lemon
Note that this approach is faster but does not provide the same flexibility as includes()
or indexOf()
.