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;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
findIndex | |
for loop |
Test name | Executions per second |
---|---|
findIndex | 8649.1 Ops/sec |
for loop | 47613.8 Ops/sec |
Let's break down the provided JSON data and explain what's being tested in the benchmark.
Benchmark Definition
The benchmark is testing two approaches to find an object in an array:
arr.findIndex((itm) => itm.id === foo);
for
loop: for (let i = 0; i < arr.length; i++) { if (arr[i].id === foo) break; }
Options Compared
The benchmark is comparing the performance of these two approaches:
arr.findIndex()
: This method returns the index of the first element in the array that satisfies the provided condition. If no elements satisfy the condition, it returns -1.for
loop: This approach uses a manual loop to iterate through the array and checks each element's property until it finds the desired one.Pros and Cons
arr.findIndex()
:
Pros:
Cons:
foo
is not found in the arrayTraditional for
loop:
Pros:
arr.findIndex()
might not work (e.g., older browsers)Cons:
arr.findIndex()
arr.findIndex()
for large arraysOther Considerations
15000
elements), which may affect the performance difference between these two approaches.arr.findIndex()
to make it more efficient, but this might not be the case for other browsers or older versions.Library and Special JS Features
There is no library explicitly mentioned in the provided code. However, Math.random()
is used to generate a random index (foo
), which suggests that JavaScript's built-in random
function is being utilized. This is a standard feature of the JavaScript language and does not require any additional libraries.
Special JS Feature or Syntax
The use of map()
in the script preparation code (arr.map((el, idx) => el.id = idx);
) is an example of JavaScript's built-in map()
function, which creates a new array with the results of applying a provided function to each element. This feature is not specific to any library or syntax extension.
Alternatives
Other alternatives for finding an object in an array include:
find()
instead of findIndex()
: returns the first matching element or undefined if no elements match._.find(arr, (elm) => elm.id === foo)
), which provides a more concise and expressive way to perform array searches.next()
or PHP's array_search()
.These alternatives may have their own performance characteristics and are not directly comparable to the arr.findIndex()
approach.