var arr = [];
var i = 0;
while (i <= 1E5) arr[i] = i++;
const item = arr.find(item => item === 1E5);
const index = arr.indexOf(1E5);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.find | |
Array.indexOf |
Test name | Executions per second |
---|---|
Array.find | 4980.7 Ops/sec |
Array.indexOf | 151867.2 Ops/sec |
Let's break down the provided benchmark and its test cases.
Benchmark Overview
The benchmark compares two JavaScript methods for finding a specific element in an array: Array.prototype.find()
and Array.prototype.indexOf()
. The tests are designed to measure the performance difference between these two methods.
Script Preparation Code
The script preparation code creates an array arr
with 100,000 elements, where each element is initialized to its index value (i
). This array will be used as input for both tests.
var arr = [];
var i = 0;
while (i <= 1E5) {
arr[i] = i++;
}
This code creates a large array with a linear progression of values, which is expected to be present in the array during the benchmarking process.
Benchmark Definition
The Benchmark Definition
section contains two test cases:
find()
method to find an element with a value equal to 100,000.const item = arr.find(item => item === 1E5);
This method returns the first element in the array that satisfies the provided condition.
indexOf()
method to find the index of an element with a value equal to 100,000.const index = arr.indexOf(1E5);
This method returns the index of the first occurrence of the specified value in the array.
Options Compared
The benchmark compares two options:
Pros and Cons
indexOf()
.indexOf()
due to its callback-based approach.find()
since it uses a direct comparison.Library and Special JS Features
There are no external libraries used in this benchmark. However, it's worth noting that find()
was introduced in ECMAScript 2015 (ES6), so it may not be supported in older browsers or environments.
Other Alternatives
If you're interested in exploring other methods for finding elements in an array, here are a few alternatives:
true
if at least one element satisfies the condition.true
if all elements satisfy the condition.Keep in mind that these alternatives may have different performance characteristics compared to find()
and indexOf()
.