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(el => el.id === foo);
var index = arr.map(el => el.id).indexOf(foo);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.findIndex | |
Array.prototype.map + Array.prototype.indexOf |
Test name | Executions per second |
---|---|
Array.prototype.findIndex | 310.7 Ops/sec |
Array.prototype.map + Array.prototype.indexOf | 1666.1 Ops/sec |
I'd be happy to help explain the benchmark.
Benchmark Overview
The provided JSON represents a JavaScript microbenchmark on the comparison of two approaches to find the index of an element in an array: Array.prototype.findIndex
and Array.prototype.map + Array.prototype.indexOf
. The benchmark aims to determine which approach is faster for large arrays.
Options Compared
Two options are compared:
Array.prototype.findIndex
: This method returns the index of the first element that satisfies the provided callback function.Array.prototype.map + Array.prototype.indexOf
: This approach involves mapping each element in the array to a new value, and then finding the index of the desired value using indexOf
.Pros and Cons
Array.prototype.findIndex
:Array.prototype.map + Array.prototype.indexOf
:findIndex
, and potentially slower for large arrays.Library/Utilities
In this benchmark, there is no explicit library or utility mentioned. Both Array.prototype.findIndex
and Array.prototype.map + Array.prototype.indexOf
are part of the standard JavaScript API.
However, if we were to extend this benchmark to include additional libraries or utilities, some options might include:
findIndex
, which can be used as an alternative to Array.prototype.findIndex
.Special JS Feature/Syntax
The benchmark does not explicitly test any special JavaScript features or syntax. It solely focuses on comparing the performance of two standard array methods.
However, it's worth noting that certain features like for...of
loops or async/await
syntax are not tested here, as they are not directly related to the comparison of these two specific array methods.
Alternatives
If you were to extend this benchmark to compare other approaches for finding the index of an element in an array, some alternatives might include: