var arr = ['one', 'two', 'three'];
var test = 'three';
arr.findIndex(val => val === test)
arr.indexOf(test)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
findIndex | |
indexOf |
Test name | Executions per second |
---|---|
findIndex | 2323308.0 Ops/sec |
indexOf | 4266060.0 Ops/sec |
Let's dive into the explanation of what's being tested.
Benchmark Overview
The benchmark is testing two different JavaScript methods: indexOf
and findIndex
. Both methods are used to find the index of an element in an array, but they have some differences under the hood.
Test Cases
There are two individual test cases:
findIndex
method, which takes a callback function as its argument. The callback function is called for each element in the array until it finds the desired element (test
) and returns its index.indexOf
method, which directly searches for the desired element in the array.Library/Feature Used
In this benchmark, no specific library or feature is used. The test cases are pure JavaScript implementations.
Options Compared
The two options being compared are:
findIndex
(callback-based)indexOf
(traditional)Pros and Cons of Each Approach
Here's a brief summary of the pros and cons of each approach:
Other Considerations
When choosing between findIndex
and indexOf
, consider the following factors:
findIndex
with a custom callback might be more efficient.findIndex
might have an edge due to its ability to stop searching once it finds the desired element.indexOf
.Alternatives
If you're not satisfied with these options or want more flexibility, consider using a library like:
findIndex
: Provides additional features and customization options for finding indices.That's it!