var arr = [];
var i = 0;
while (i <= 1E5) arr[i] = i++;
const index = arr.findIndex(item => item === 1E5);
var index = -1
for(var i = 0; i < arr.length; i++) {
if(arr[i] === 1E5) {
index = i;
break;
}
}
let index = -1;
let i = 0
const len = arr.length;
while (++i < len) {
if (arr[i] === 1E5) {
index = i
break;
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.findIndex | |
For loop | |
While loop |
Test name | Executions per second |
---|---|
Array.prototype.findIndex | 3141.1 Ops/sec |
For loop | 11428.8 Ops/sec |
While loop | 8410.7 Ops/sec |
Let's break down the benchmark and its various components.
Benchmark Definition JSON
The provided benchmark
object defines two test cases:
arr
with 100,000 elements and assigns each element a unique integer value from 0 to 99,999.Individual Test Cases
The benchmark defines three test cases:
const index = arr.findIndex(item => item === 1E5);
1E5
) in the generated array using the findIndex
method.var index = -1; for(var i = 0; i < arr.length; i++) { if(arr[i] === 1E5) { index = i; break; } }
let index = -1; let i = 0; const len = arr.length; while (++i < len) { if (arr[i] === 1E5) { index = i; break; } }
Library
None of these test cases use a library specifically. They are built-in JavaScript methods.
Special JS feature or syntax
The findIndex
method uses a modern JavaScript feature called arrow functions, which were introduced in ECMAScript 2015 (ES6). Arrow functions provide a concise way to define small, one-time use functions. In this case, the arrow function is used as a callback for the findIndex
method.
Browser and Environment
The benchmark results are from running the benchmarks on a Firefox 117 browser on a Mac OS X 10.15 desktop environment.
Other Alternatives
To measure which of these approaches is faster, one could also use:
Keep in mind that the results may vary depending on the specific environment and hardware used.