var arr = new Array(1000000);
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;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
findIndex | |
for loop |
Test name | Executions per second |
---|---|
findIndex | 6.1 Ops/sec |
for loop | 2.3 Ops/sec |
Let's break down the provided JSON and explain what's being tested.
Benchmark Overview
The benchmark is comparing two approaches to find an element in a large array: using Array.prototype.findIndex()
(also known as "findIndex") or a traditional for loop. The goal is to determine which approach is faster.
Options Compared
Two options are compared:
arr.findIndex((itm) => itm.id === foo);
: This uses the findIndex()
method, which returns the index of the first element in the array that satisfies the provided condition (in this case, foo
). If no element is found, -1 is returned.for (let i = 0; i < arr.length; i++) {\r\n if (arr[i].id === foo) break;\r\n}
: This uses a traditional for loop to iterate through the array and find the first element that matches foo
.Pros and Cons
Library Used
In this benchmark, Array.prototype.findIndex()
is used. The findIndex()
method is a part of the ECMAScript standard and is implemented by most modern browsers, including Chrome 106.
Special JS Feature or Syntax
There are no special JavaScript features or syntax mentioned in this benchmark.
Other Considerations
findIndex()
is widely supported, older browsers may not have it available or may behave differently.Alternatives
Other approaches to finding an element in a large array might include:
Keep in mind that these alternatives might not be as straightforward or easy to implement as findIndex()
or a for loop.