var arr = [];
var i = 0;
while (i <= 1E5) arr[i] = i++;
const index = arr.indexOf(1E5)
const item = arr[index]
const index = arr.findIndex(item => item === 1E5);
const item = arr[index]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Get item by index with Array.indexOf | |
Get item by index with Array.findIndex |
Test name | Executions per second |
---|---|
Get item by index with Array.indexOf | 12761.4 Ops/sec |
Get item by index with Array.findIndex | 3595.4 Ops/sec |
Let's break down the JavaScript microbenchmark test case.
What is being tested?
The benchmark tests two ways to retrieve an item from an array in JavaScript:
Array.indexOf()
: This method returns the index of the specified value (in this case, 100,000) if it exists in the array.Array.findIndex()
: This method returns the index of the first element that satisfies the provided condition (in this case, a strict equality check with 100,000).Options compared
The two options being compared are:
Array.indexOf()
stops searching as soon as it finds the value, while Array.findIndex()
continues searching even after finding the value.Array.indexOf()
and Array.findIndex()
is their behavior when they don't find the specified value.Pros and Cons
In general, Array.indexOf()
is faster and more suitable for cases where you only need to find the first occurrence of a value. Array.findIndex()
, on the other hand, is useful when you need to process all elements that match the condition.
Library usage
Neither Array.indexOf()
nor Array.findIndex()
use any external libraries.
Special JS feature or syntax
There is no special JavaScript feature or syntax used in this benchmark. However, it's worth noting that both methods work with modern browsers and Node.js, which means you don't need to worry about older browser versions.
Other alternatives
If you're looking for alternative ways to retrieve an item from an array in JavaScript, you might consider using:
true
as soon as it finds the first element that matches the condition, similar to Array.indexOf()
.Keep in mind that these alternatives might not be suitable for all use cases, and the choice of implementation depends on your specific requirements and constraints.