var arr = new Array(15000);
arr.fill({ id: 0 });
arr = arr.map((el, idx) => el.id = idx);
var foo = Math.floor(Math.random() * 15000);
var startIndex = 7500;
arr.findIndex((m,i) => i >= startIndex && m.id === foo);
for (let i = startIndex; 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 | 3885.9 Ops/sec |
for loop | 38790.5 Ops/sec |
The benchmark defined in the provided JSON tests the performance of two different methods for finding an object in an array, specifically evaluating findIndex
against a traditional for
loop. This comparison is important in understanding which approach offers better performance when searching through an array in JavaScript.
findIndex Method:
arr.findIndex((m, i) => i >= startIndex && m.id === foo);
This method takes a callback function that is executed for each element in the array. It returns the index of the first element in the array that satisfies the provided testing function. If no elements satisfy the testing function, it returns -1.
For Loop:
for (let i = startIndex; i < arr.length; i++) {
if (arr[i].id === foo) break;
}
This traditional loop iterates over the array starting from a specified index (startIndex
) and checks if any object's id
matches the value of foo
. If it finds a match, it breaks out of the loop.
Pros:
Cons:
Pros:
Cons:
findIndex
method is part of the ECMAScript 2015 (ES6) standard, thus may not be supported in older environments, though modern browsers and environments widely support it.for
loop is a fundamental construct and is guaranteed to work across all JavaScript environments.The performance results show that the "for loop" runs significantly faster than findIndex
, with approximately 38,790 vs. 3,885 executions per second, respectively. This result illustrates the practical impact of the design choices made in JavaScript for these two approaches.
forEach:
forEach
method, but it cannot break out of the loop once a condition is met, making it less efficient for search operations.Other Loop Constructs:
for...of
: This can be another alternative for iterating over arrays, but like forEach
, it cannot terminate early like a traditional for loop
.Utilizing newer data structures:
In essence, the benchmark shows that while findIndex
offers clarity and ease of use, the traditional for
loop remains a powerful alternative for performance-critical operations in JavaScript array manipulation.