var arr = new Array(15000);
arr.fill([ 500 ]);
arr = arr.map((el, idx) => el.id = idx);
var foo = Math.floor(Math.random() * 15000);
arr.findIndex((itm) => itm.id === foo);
for (let i = 0; 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 | 134.5 Ops/sec |
for loop | 55.0 Ops/sec |
Let's dive into the Benchmark Definition and test cases.
Benchmark Overview
The benchmark is designed to compare two approaches for finding an object in a large array:
findIndex
method with a callback function.for
loop.Options Compared
The two options being compared are:
arr.findIndex((itm) => itm.id === foo);
: This is the findIndex
method, which returns the index of the first element in the array that satisfies the provided condition.for (let i = 0; i < arr.length; i++) { ... }
: This is a traditional for
loop that iterates through the array and checks each element's id
property.Pros and Cons
findIndex
method.for
loop:findIndex
method.Library
In this benchmark, no libraries are explicitly mentioned. However, the findIndex
method is a built-in JavaScript function that uses the V8 engine (specifically, SpiderMonkey) for its implementation.
Special JS Feature or Syntax
The benchmark utilizes the let
and const
keywords with block scope, which was introduced in ECMAScript 2015 (ES6). The =>
symbol is used as an arrow function syntax. These features are not essential to understanding the benchmark but demonstrate modern JavaScript capabilities.
Other Alternatives
If you wanted to write a similar benchmark for this scenario, you could also use:
Array.prototype.some()
: This method returns true
if at least one element in the array satisfies the condition.String.prototype.indexOf()
or String.prototype.search()
Buffer.find()
(for Node.js and other platforms that support it)