var arr = [new Array(15000)].map((el, idx) => ({
id: idx
}));
const foo = Math.floor(Math.random() * 15000);
arr.findIndex((itm) => itm.id === foo);
const foo = Math.floor(Math.random() * 15000);
for (let i = 0, j = arr.length; i < j; ++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 | 120265.6 Ops/sec |
for loop | 2929.1 Ops/sec |
Let's break down the provided benchmark and explain what is being tested.
Benchmark Overview
The benchmark is designed to compare two approaches for finding an object in an array: using the findIndex
method or a traditional for
loop.
Script Preparation Code
The script preparation code creates an array of 15,000 objects with an "id" property:
var arr = [...new Array(15000)].map((el, idx) => ({ id: idx }));
This array is used as the input for both test cases.
Html Preparation Code
There is no HTML preparation code provided, which means that this benchmark is purely JavaScript-based and does not involve any DOM manipulation or rendering.
Test Cases
The two test cases are:
findIndex
:const foo = Math.floor(Math.random() * 15000);
arr.findIndex((itm) => itm.id === foo);
This test case uses the findIndex
method to find an object in the array with a matching "id". The foo
variable is randomly generated and used as the target value.
for loop
:const foo = Math.floor(Math.random() * 15000);
for (let i = 0, j = arr.length; i < j; ++i) {
if (arr[i].id === foo) break;
}
This test case uses a traditional for
loop to iterate through the array and find an object with a matching "id". Again, the foo
variable is randomly generated and used as the target value.
Pros and Cons
Here are some pros and cons of each approach:
Library and Special JS Features
There is no library used in this benchmark. The findIndex
method is a native JavaScript function that has been supported since ECMAScript 2012.
Other Considerations
When designing benchmarks, it's essential to consider factors such as:
Alternatives
Other alternatives for finding an object in an array include:
forEach
: While not designed specifically for finding elements, forEach
can be used in combination with a callback function to achieve similar results.some
, every
, or filter
, which may have different performance characteristics depending on the use case.Keep in mind that this benchmark is focused on comparing two specific approaches, rather than exploring other optimization techniques or considering broader performance implications.