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(x => x.id === 0);
arr.map(x => x.id).indexOf(0);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
findIndex | |
Map + IndexOf |
Test name | Executions per second |
---|---|
findIndex | 45175.5 Ops/sec |
Map + IndexOf | 13678.2 Ops/sec |
I'd be happy to help explain the provided benchmark.
Benchmark Overview
The benchmark is designed to compare the performance of two approaches: findIndex
and map
with indexOf
. The goal is to find an element in an array that matches a specific condition.
Script Preparation Code
Before running each test case, the script prepares an array of 15,000 elements with a unique id
property. The array is then modified by mapping over it and assigning the index to each element's id
property using the arrow function (el, idx) => el.id = idx
. This step is likely done to ensure that the search space for both test cases is uniform.
Test Cases
There are two individual test cases:
findIndex
method to find an element in the array where its id
property equals 0.indexOf
method to search for the value 0 within the mapped array.Libraries and Special JS Features
Neither of these two approaches rely on any external libraries. However, it's worth noting that the arrow function syntax used in both test cases is a modern JavaScript feature introduced in ECMAScript 2015 (ES6).
Options Compared
The options being compared are:
indexOf
method.Pros and Cons of Each Approach
Other Alternatives
If you wanted to compare other approaches, here are some alternatives:
findIndex
, you could use the filter
method to create a new array with elements that satisfy the condition.Keep in mind that these alternatives might have different performance characteristics, depending on your specific use case.
Other Considerations
I hope this explanation helps!