var array = ['banana', 'sausage', 'jesus']
array.indexOf('sausage') !== 1
array.includes('sausage')
_.includes(array, 'sausage')
const inArray = (target = 'sausage', array) => {
for(let i = 0; i < array.length; i++) {
if(array[i] === target) {
return true;
}
}
return false;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
indexOf | |
includes | |
lodash | |
for |
Test name | Executions per second |
---|---|
indexOf | 12769638.0 Ops/sec |
includes | 13762992.0 Ops/sec |
lodash | 3628653.2 Ops/sec |
for | 731445888.0 Ops/sec |
Let's break down the provided benchmarking test cases.
Benchmark Definition
The benchmark measures the performance of different methods to find an element in an array:
indexOf
: Returns the index of the specified value in the array, or -1 if it is not found.includes
: Returns a boolean indicating whether an element with the specified value exists in the array._lodash.includes
(using the Lodash library): Similar to includes
, but implemented as part of the Lodash library.for
loop: A custom implementation using a traditional for
loop.Options Compared
The benchmark compares the performance of these four options:
indexOf
: Simple and widely supported, but may be slower due to its use of indexing and bounds checking.includes
: Similar simplicity to indexOf
, but with a more efficient implementation in modern browsers. However, it may not work correctly for certain edge cases or older browsers._lodash.includes
: Part of the Lodash library, which provides a comprehensive set of utility functions. This option is likely to be slower due to the overhead of the library, but offers a convenient and flexible way to perform string matching.for
loop: A custom implementation using a traditional for
loop, which requires manual iteration over the array elements. This option is likely to be the slowest, as it does not take advantage of optimized array operations or caching.
Library UsedThe Lodash library is used in the _lodash.includes
test case.
_.includes
is used as a convenient way to perform string matching without having to implement it from scratch.Special JS Feature or Syntax
None of the options in the benchmark require special JavaScript features or syntax beyond what is commonly supported by modern browsers.
Other Alternatives
If you're interested in exploring alternative approaches, here are a few options:
: This method returns
trueif at least one element in the array passes a test, and
falseotherwise. While not exactly equivalent to
includes`, it can be used as a similar optimization.&
or |
) to perform string matching quickly. However, these approaches are generally less readable and may require more expertise to implement correctly.Keep in mind that the performance differences between these options may not be dramatic, especially for small arrays. The benchmark is likely designed to highlight any significant performance differences between these approaches.