var arr = new Array(15000);
arr.fill({ id: 0 });
arr = arr.map((el, idx) => el.id = idx);
var foo = Math.floor(Math.random() * 15000);
var index = arr.findIndex( (item) => item.id === foo);
var bar = { id: foo };
var index = arr.indexOf(bar);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
findIndex | |
indexOf |
Test name | Executions per second |
---|---|
findIndex | 7102.1 Ops/sec |
indexOf | 18982.9 Ops/sec |
I'll dive into explaining the benchmark.
What is being tested?
The benchmark is comparing two methods to find an element in an array: Array.prototype.indexOf()
and Array.prototype.findIndex()
. Both methods are used to search for a specific value within the array, but they differ in how they handle the result.
Options compared:
indexOf()
: This method returns the index of the first occurrence of the specified value, or -1 if it is not found.findIndex()
: This method returns the index of the first occurrence of the specified value, or -1 if it is not found.Pros and Cons:
indexOf()
: Pros:findIndex()
: Pros:Cons:
indexOf()
: May be slower due to its search algorithm and additional checks.findIndex()
: Can be slower for large arrays, as it has to iterate through the entire array to find a match.Library usage:
None of the test cases use any libraries or external dependencies. The benchmark is purely focused on comparing the performance of these two methods within the Array prototype.
Special JS feature/syntax:
No special JavaScript features or syntax are used in this benchmark.
Other alternatives:
In addition to indexOf()
and findIndex()
, other methods can be used to search for an element in an array, such as:
Array.prototype.includes()
(introduced in ECMAScript 2015): Returns true if the array includes the specified value.for
loops or forEach()
.Keep in mind that these alternatives may have different performance characteristics and are not being tested in this benchmark.