<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.findIndex(v => v === 'sausage')
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
IndexOf | |
Includes | |
findIndex |
Test name | Executions per second |
---|---|
IndexOf | 8469570.0 Ops/sec |
Includes | 9688295.0 Ops/sec |
findIndex | 9162378.0 Ops/sec |
Let's break down the provided benchmark and its results.
What is tested?
The benchmark compares three different approaches to find if an array contains a specific value:
array.indexOf('sausage') !== 1
: This method uses the indexOf
function to search for the index of the specified element in the array. If the element is found, it returns its index; otherwise, it returns -1. The comparison with !== 1
checks if the element is present at the expected position.array.includes('sausage')
: This method uses the includes
function to check if the specified element is present in the array.array.findIndex(v => v === 'sausage')
: This method uses the findIndex
function with a callback function to find the index of the first occurrence of the specified element.Options compared
The benchmark compares these three approaches:
indexOf
: A built-in JavaScript method that searches for the index of a specific value in an array.includes
: A more recent addition to the JavaScript standard library, introduced in ECMAScript 2015 (ES6), which provides a simpler and more efficient way to check if an array contains a specified value.findIndex
: Another built-in JavaScript method that finds the index of the first occurrence of a specific value in an array.Pros and cons
indexOf
:includes
for large arrays, as it uses linear search.includes
:indexOf
, especially for large arrays. It also provides a simpler syntax.findIndex
:indexOf
, as it allows searching from the beginning of the array.includes
for simple searches, as it iterates over the entire array.Library usage
The benchmark uses the popular JavaScript utility library Lodash, version 4.17.5, which provides a findIndex
function. Lodash is widely used and well-maintained, making it a good choice for this benchmark.
Special JS features or syntax
None mentioned in this specific benchmark. However, some older browsers might not support modern JavaScript features like includes
.
Other alternatives
For comparing performance, other approaches could include:
forEach
or map
to iterate over the array and check each element manually.Keep in mind that these alternatives might not be as efficient or well-documented as the standard methods and libraries used in this benchmark.