var arr = [];
var i = 0;
while (i <= 1E5) arr[i] = i++;
const item = arr.find(item => item == 1E5);
const index = arr.findIndex(item => item == 1E5);
const index = arr.indexOf(1E5);
const included = arr.includes(1E5);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
find | |
findIndex | |
indexOf | |
includes |
Test name | Executions per second |
---|---|
find | 1775.5 Ops/sec |
findIndex | 1792.7 Ops/sec |
indexOf | 7024.1 Ops/sec |
includes | 4738.3 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares the performance of four different methods to find an element in an array:
indexOf
includes
findIndex
find
These methods are used to search for a specific value within an array.
Options Compared
Each method has its own way of searching for the element, and we'll compare their performance:
indexOf
: This method returns the index of the first occurrence of the specified value within the array. If the value is not found, it returns -1
.includes
: This method checks if the array includes the specified value without returning an index.findIndex
: Similar to indexOf
, but this method only returns the index of the first occurrence of the specified value in a strictly increasing sequence. If no such element is found, it returns -1
.find
: This method returns the first element that satisfies the provided testing function.Pros and Cons
Here's a brief summary of each method's pros and cons:
indexOf
:includes
:indexOf
or findIndex
, especially for large arrays.findIndex
:indexOf
for small arrays and may be more efficient than includes
.find
:Library and Purpose
None of these methods rely on external libraries. They are native JavaScript functions.
Special JS Feature or Syntax
Other Alternatives
For searching arrays, other alternatives include:
Array.prototype.some()
for a more concise implementationBinary Search
for very large arrays (not tested in this benchmark)The provided benchmark should give an idea of how these methods compare in terms of performance, but keep in mind that actual performance may vary depending on the specific use case and environment.