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);
const length = arr.length;
for (let i = 0; i < 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 | 1326.8 Ops/sec |
for loop | 714.4 Ops/sec |
Let's break down the provided benchmark and its options.
Benchmark Overview
The provided JSON represents a JavaScript microbenchmark test case on MeasureThat.net. The test aims to compare two different approaches for finding an element in an array: using the Array.prototype.findIndex()
method or a traditional for
loop.
Options Being Compared
The two options being compared are:
foo === itm.id
). If no such element exists, it returns -1
.for
loop to iterate through the elements of the array and checks each element's id
property until it finds a match.Pros and Cons of Each Approach
findIndex():
Pros:
Cons:
foo
Traditional For Loop:
Pros:
Cons:
Library and Syntax Considerations
In this benchmark, the Array.prototype.findIndex()
method is used, which is a part of the standard JavaScript library. There are no custom libraries or special syntax features involved.
Other Alternatives
Some other approaches for finding an element in an array include:
Array.prototype.indexOf()
, which returns the index of the first occurrence (instead of -1
if not found)Array.prototype.reduce()
and Math.min()
to find the smallest indexHowever, these alternatives are likely to be slower or less efficient than the findIndex()
method and traditional for loop approaches.
Benchmark Preparation Code
The preparation code provided creates an array of 15,000 objects with unique id
properties using the Array.prototype.fill()
and Array.prototype.map()
methods. It then sets a random value for foo
to test in the search.
Test Cases
The benchmark consists of two individual test cases:
Array.prototype.findIndex()
method with the provided condition (foo === itm.id
)for
loop approach using an index variable and array bounds checkingThese test cases are likely executed multiple times to generate a set of execution results, which is then displayed on MeasureThat.net.