<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var array = ['banana', 'sausage', 'jesus', 'something']
array.indexOf('sausage') !== 1
array.includes('sausage')
array.some(v => v === 'sausage')
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
IndexOf | |
Includes | |
some |
Test name | Executions per second |
---|---|
IndexOf | 27006524.0 Ops/sec |
Includes | 29388080.0 Ops/sec |
some | 27450502.0 Ops/sec |
Let's break down the benchmark and explain what's being tested, compared, and their pros and cons.
What is being tested?
The benchmark compares three ways to find if an array contains a value:
array.indexOf('sausage') !== 1
array.includes('sausage')
array.some(v => v === 'sausage')
These methods are used to determine whether the string 'sausage'
exists in the array.
Comparison of options
Here's a brief overview of each option:
array.indexOf('sausage') !== 1
'sausage'
in the array, or -1
if not found.NaN
(Not a Number) instead of -1
for certain edge cases.array.includes('sausage')
true
if the array includes 'sausage'
, and false
otherwise.indexOf
.indexOf
due to additional checks.array.some(v => v === 'sausage')
'sausage'
.indexOf
or includes
.Library: Lodash
The benchmark includes a reference to the Lodash library (https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js
). Lodash is a utility library that provides a wide range of functions for working with arrays, objects, and other data structures. In this case, the includes
function from Lodash is used in the benchmark.
Special JS features
There are no special JavaScript features or syntaxes being tested in this benchmark. All methods use standard JavaScript syntax and semantics.
Alternatives
Other alternatives to these methods could include:
Array.prototype.includes
is supported by modern browsers).It's worth noting that the some
method may be slower than the other two options due to the use of a callback function. However, it provides a concise and expressive way to solve this problem, making it a popular choice among developers.