var arr = [];
var i = 0;
while (i <= 1E5) arr[i] = i++;
const item = arr.find(item => item == 15);
const index = arr.findIndex(item => item == 15);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.find | |
Array.prototype.findIndex |
Test name | Executions per second |
---|---|
Array.prototype.find | 103849912.0 Ops/sec |
Array.prototype.findIndex | 107191480.0 Ops/sec |
Let's break down the benchmark and its options.
Benchmark Definition
The benchmark is designed to compare two methods for finding the first element in an array that matches a specific condition: find
and findIndex
. Both methods are part of the Array prototype.
Options Compared
The main difference between find
and findIndex
lies in their behavior when no elements match the condition:
find
: Returns undefined
if no element is found. It stops searching as soon as it finds a match.findIndex
: Returns -1
if no element is found. It continues searching until it finds an element or reaches the end of the array.Pros and Cons
find
might be slightly faster because it stops searching as soon as it finds a match.findIndex
is safer because it doesn't rely on returning undefined
, which can cause issues if you're not expecting an empty array. However, if you know that the array will always have at least one element, find
might be faster.Library Used
In this benchmark, no external library is used.
Special JavaScript Features/Syntax
This benchmark doesn't use any special JavaScript features or syntax beyond what's available in modern browsers.
Other Alternatives
If you need to find the first element in an array that matches a condition, there are other alternatives:
for
loop and return as soon as you find a match. This approach is similar to find
, but it's not optimized like the built-in methods.some()
or every()
: While these methods don't directly help with finding the first element, they can be used in conjunction with another method to achieve a similar result.Overall, both find
and findIndex
are suitable for this use case. If you need to find one specific element and don't mind potentially getting undefined
, find
might be faster. However, if you're working with arrays that may not have any matches or want the safety net of returning a numeric value regardless of whether an element is found, findIndex
is a better choice.
As for the benchmark results provided, they show the execution speeds for both methods on Opera 82 running on Windows. The browser returns more executions per second with findIndex
, indicating that it's faster in this specific test case.