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);
let output = -1
for (const [index, item] of arr.entries()) {
if (item.id = foo) {
output = index;
break
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
findIndex | |
forOf loop |
Test name | Executions per second |
---|---|
findIndex | 648.3 Ops/sec |
forOf loop | 1065789.2 Ops/sec |
Let's break down the benchmark and explain what's being tested, compared, and the pros/cons of each approach.
Benchmark Overview
The benchmark is comparing two ways to find an element in an array:
Array.prototype.findIndex()
(findIndex)for...of
loopOptions Compared
Pros and Cons of Each Approach
FindIndex:
Pros:
Cons:
for...of
loop for small arrays due to JavaScript's caching and optimization mechanismsFor...of Loop:
Pros:
Cons:
Library/Features Used
In this benchmark, no specific libraries are used beyond the built-in Array.prototype.findIndex()
method. However, it's worth noting that some JavaScript engines and versions may have different optimizations or implementation details for these methods.
Special JS Features/Syntax
The benchmark uses the following feature:
findIndex
test case is an arrow function ((itm) => itm.id === foo
). This feature allows for concise and readable code, while also avoiding the use of traditional function expressions.for...of
loop may benefit from this caching due to its more explicit nature.Other Alternatives
If you're looking for alternative approaches, consider the following:
findIndex
, you can use the reduce()
method to find the index of the element. This approach is often faster and more readable than traditional loops.Symbol.iterator
and implementing the next()
method.Keep in mind that these alternatives may have different performance characteristics or use cases, so it's essential to test and choose the best approach for your specific problem.