var arr = new Array(15000);
arr.fill({ id: 0 });
arr = arr.map((el, idx) => el.id = idx);
var foo = Math.floor(Math.random() * 15000);
arr.findIndex((itm) => itm.id === foo);
for (let i = 0; i < arr.length; i++) {
if (arr[i].id === foo) break;
}
arr.some((itm) => itm.id === foo);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
findIndex | |
for loop | |
some |
Test name | Executions per second |
---|---|
findIndex | 1933.5 Ops/sec |
for loop | 400.5 Ops/sec |
some | 906.5 Ops/sec |
Let's break down the provided benchmark and its components.
Benchmark Description
The benchmark compares three approaches to find an element in an array:
arr.findIndex((itm) => itm.id === foo)
- uses the findIndex
methodfor (let i = 0; i < arr.length; i++) {\r\n if (arr[i].id === foo) break;\r\n}
- uses a traditional for looparr.some((itm) => itm.id === foo)
- uses the some
methodOptions Compared
findIndex
: uses the findIndex
method, which returns the index of the first element that satisfies the condition.for loop
: uses a traditional for loop to iterate through the array and check each element.some
: uses the some
method, which returns true if at least one element in the array satisfies the condition.Pros and Cons
findIndex
:for loop
:some
:findIndex
, but returns true instead of an index. Can be faster in some cases due to optimized implementation.Library/Functionality
None of the benchmarked approaches use external libraries or functions.
Special JS Feature/Syntax
There is no special JavaScript feature or syntax used in this benchmark. All approaches are standard and well-supported by most browsers.
Alternatives
Other alternatives to compare could be:
includes()
method instead of findIndex
or some
filter()
, map()
, or reduce()
These alternatives would require additional benchmark setup and results, but could provide further insights into optimal approaches for specific use cases.