<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var array = ['banana', 'sausage', 'jesus']
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 | 594208768.0 Ops/sec |
Includes | 197759072.0 Ops/sec |
some | 147400784.0 Ops/sec |
Let's dive into the provided benchmark and explain what's being tested.
Benchmark Overview
The website MeasureThat.net
provides a platform for users to create and run JavaScript microbenchmarks. The current benchmark compares three approaches to find if an array contains a value: array.indexOf()
, array.includes()
, and array.some()
.
What is being tested?
In the provided benchmark definition, three test cases are defined:
IndexOf
: Checks if the array contains a specific value using array.indexOf('sausage')
.Includes
: Checks if the array contains a specific value using array.includes('sausage')
.some
: Uses a callback function to check if any element in the array matches a condition (v => v === 'sausage'
).Options compared
The benchmark compares the performance of these three approaches:
indexOf()
: Returns the index of the first occurrence of the specified value, or -1
if it's not found.includes()
: Returns true
if the array contains the specified value, and false
otherwise.some()
: Returns true
as soon as any element in the array matches the condition (in this case, v === 'sausage'
), or false
if no elements match.Pros and Cons of each approach
indexOf()
:includes()
: ( Introduced in ECMAScript 2019)some()
:indexOf()
or includes()
, especially for large arrays, since it has to iterate through the entire array.Library usage
The benchmark includes a reference to the lodash.js
library:
<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
Lodash
is a popular utility library for JavaScript that provides various helper functions, including ones for array manipulation.
Special JS feature or syntax
The benchmark uses the some()
method with an arrow function (v => v === 'sausage'
). This syntax was introduced in ECMAScript 2015 (ES6) and allows for concise and expressive code. The arrow function is equivalent to a traditional function declaration, but with some benefits, such as reduced overhead.
Other alternatives
If indexOf()
or includes()
are not suitable for the use case, other alternatives could be:
However, it's worth noting that these approaches may be slower and less efficient than the ones being compared in this benchmark.