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((num) => num === foo);
var index = arr.indexOf(foo);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
findIndex | |
indexOf |
Test name | Executions per second |
---|---|
findIndex | 3960.9 Ops/sec |
indexOf | 329645.1 Ops/sec |
Let's break down the JavaScript microbenchmark on MeasureThat.net.
Benchmark Overview
The benchmark compares the performance of two methods: Array.prototype.findIndex
and Array.prototype.indexOf
. Both methods are used to find the index of a specific element in an array. The test creates a large array with 15,000 elements, each containing a unique identifier, and then randomly selects one element using the Math.random()
function.
Options Compared
The two options being compared are:
Array.prototype.findIndex
: This method returns the index of the first element in the array that satisfies the provided condition (in this case, the condition is num === foo
). If no such element exists, it returns -1
.Array.prototype.indexOf
: This method returns the index of the first occurrence of a specified value in the array.Pros and Cons
Array.prototype.findIndex
has some advantages over Array.prototype.indexOf
:-1
if no element satisfies the condition, whereas indexOf
throws an error or returns -1
.Array.prototype.indexOf
has some advantages over findIndex
:Library and Purpose
The benchmark uses the JavaScript standard library's built-in methods: Array.prototype.findIndex
and Array.prototype.indexOf
.
Special JS Feature or Syntax
There are no special JS features or syntax used in this benchmark.
Other Considerations
When choosing between findIndex
and indexOf
, consider the following:
findIndex
.-1
or an error).indexOf
.Alternatives
Other methods that could be used for finding the index of an element in an array include:
for (var i = 0; i < arr.length; i++) { if (arr[i] === foo) { break; } }
Array.prototype.includes
: return arr.indexOf(foo)
is equivalent to arr.includes(foo)
_findIndex(arr, foo)
Keep in mind that these alternatives may have different performance characteristics and usage scenarios compared to findIndex
and indexOf
.