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 item = arr[index]
const item = arr.filter(item => item == 1E5)[0];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.find | |
Array.prototype.findIndex | |
Array.prototype.filter |
Test name | Executions per second |
---|---|
Array.prototype.find | 979.5 Ops/sec |
Array.prototype.findIndex | 999.2 Ops/sec |
Array.prototype.filter | 915.9 Ops/sec |
Let's break down what is being tested in this benchmark and the options being compared.
Benchmark Context
The benchmark measures the performance of three JavaScript methods: find
, findIndex
, and filter
. These methods are used to search for a specific value within an array. The benchmark creates a large array (arr
) with values from 0 to 100,000 using a while loop.
Method Options being Compared
The benchmark compares the performance of these three methods:
find
: Returns the first element in the array that satisfies the provided testing function.findIndex
: Returns the index of the first element in the array that satisfies the provided testing function.filter
: Creates a new array with all elements from the original array that satisfy the provided testing function.Pros and Cons of Each Approach
find
:undefined
if no element is found, which can lead to errors if not handled properly.findIndex
:filter
:find
and findIndex
if the filtering condition is expensive to compute, as it doesn't require a callback function like these two methods.Library Used
None of the methods in this benchmark use any external libraries. However, some browsers may have built-in optimizations or features that affect the performance of these methods.
Special JS Features or Syntax
The benchmark doesn't mention any special JavaScript features or syntax, such as async/await, Promises, or generator functions.
Other Considerations
When choosing between find
, findIndex
, and filter
, consider the following:
filter
may be more readable.filter
might be more efficient.Alternatives
If you don't need the exact functionality provided by find
, findIndex
, and filter
, consider alternative approaches:
some()
or every()
.