var arr = [];
var i = 0;
while (i <= 1E5) arr[i] = i++;
const item = arr.find(item => item == 1E5);
const item = arr[arr.indexOf(1E5)];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype().find() | |
Array.prototype().indexof() |
Test name | Executions per second |
---|---|
Array.prototype().find() | 930.7 Ops/sec |
Array.prototype().indexof() | 4935.3 Ops/sec |
Measuring JavaScript performance is an essential task, especially when comparing different approaches to achieve the same result.
Benchmark Overview
The provided benchmark compares two methods for finding or retrieving a specific item in an array: find()
and indexOf()
. The test cases use a predefined array generated by the "Script Preparation Code" to populate the array with values from 0 to 100,000.
Options Compared
item === 1E5
). If no elements match, it returns undefined
.1E5
) in the array. If the value is not found, it returns -1
.Pros and Cons
Library and Purpose
There are no external libraries used in this benchmark. Both find()
and indexOf()
are built-in methods of the Array prototype in JavaScript.
Special JS Feature/Syntax
This benchmark doesn't use any special JavaScript features or syntax beyond the standard array methods and arithmetic operations (e.g., exponentiation).
Other Alternatives
If you need to find a specific item in an array, consider the following alternatives:
find()
, but returns true
if the element is found anywhere in the array.indexOf()
).Benchmark Result Interpretation
The provided benchmark results show the execution times for each test case on a Chrome 94 browser with a desktop platform and Mac OS X 10.15.7 operating system. The first result shows indexOf()
being faster, while the second result shows find()
being slightly slower. However, these results may vary depending on your specific use case, array size, and hardware configuration.
In conclusion, when comparing find()
and indexOf()
, consider the trade-off between readability and performance. If you need a more straightforward solution with better performance, using indexOf()
might be suitable. For cases where code readability is crucial or the array doesn't require frequent updates, find()
could be a better choice.