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 |
---|---|
while | |
Array.indexOf |
Test name | Executions per second |
---|---|
while | 5877.9 Ops/sec |
Array.indexOf | 25652262.0 Ops/sec |
Let's break down the provided benchmark and explain what is being tested.
What is being tested?
The benchmark is testing two approaches to find an item in an array: find()
and indexOf()
. The test cases are comparing the performance of these two methods on a large array generated by a while loop.
Options compared
Two options are being compared:
find()
: A method that returns the first element in the array that satisfies the provided condition.indexOf()
: A method that returns the index of the first occurrence of the specified value in the array, or -1 if it is not found.Pros and Cons
find()
: This method can be faster for small arrays since it doesn't require searching from the beginning. However, its performance can degrade significantly for large arrays because it has to traverse the entire array to find the first match.indexOf()
**: This method is generally faster for large arrays because it uses a linear search algorithm that starts from the beginning of the array and checks each element in sequence.In this benchmark, since the array size is relatively small (1E5), the difference in performance between find()
and indexOf()
might not be significant. However, as the array size increases, indexOf()
will likely outperform find()
.
The use of while
loop to generate a large array can also affect performance since it requires more iterations than an equivalent Array.prototype.fill()
or new Array(size).fill()
Library and its purpose
None. No external library is being used in this benchmark.
Special JS feature or syntax
Other alternatives
Alternatives to find()
and indexOf()
include:
filter()
: Returns a new array with all elements that pass the test implemented by the provided function.includes()
: Returns true if an array has at least one element that satisfies the condition, otherwise returns false.Benchmark preparation code
The script preparation code generates a large array with values from 0 to 1E5 using a while loop. The while (i <= 1E5)
loop iterates from 0 to 1E5, assigns each value to the array at index i
, and increments i
for the next iteration.
Individual test cases
The benchmark consists of two individual test cases:
while
: Tests the performance of the find()
method.Array.indexOf()
: Tests the performance of the indexOf()
method.