var arr = [];
var i = 0;
while (i <= 1E5) arr[i] = String(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 | 708.3 Ops/sec |
Array.indexOf | 71945.1 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares two methods for finding an element in an array: Array.prototype.find()
and Array.prototype.indexOf()
. Both methods are used to locate a specific value (1E5
) within the array.
Options Compared
Two options are compared:
Array.prototype.find()
: This method returns the first element in the array that satisfies the provided testing function.Array.prototype.indexOf()
: This method returns the index of the first occurrence of the specified value in the array.Pros and Cons
Array.prototype.find()
indexOf
, as it takes a callback function to specify the condition for finding the element.undefined
if no element is found.Array.prototype.indexOf()
find()
for large arrays, as it uses a linear search algorithm to find the index of the first occurrence.find()
, as it requires specifying the value to search for explicitly.Other Considerations
Array.prototype.find()
method was introduced in ECMAScript 2015 (ES6) and is now a part of the standard language specification.Array.prototype.indexOf()
method has been available since ECMAScript 1999 (ES3).Library Used
None, as this benchmark only uses built-in JavaScript methods.
Special JS Feature or Syntax
No special features or syntax are used in this benchmark. Both methods use a simple array and the 1E5
value, which is a numeric literal.
Other Alternatives
If you need to find an element in an array but don't want to use Array.prototype.find()
or Array.prototype.indexOf()
, you can consider using other approaches:
for...of
loop to iterate through the array and check each element manually.However, these alternatives are likely to be less efficient and less concise than using Array.prototype.find()
or Array.prototype.indexOf()
.