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.prototype.find | |
Array.prototype.findIndex |
Test name | Executions per second |
---|---|
Array.prototype.find | 13058.8 Ops/sec |
Array.prototype.findIndex | 150280.0 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Overview
The benchmark is designed to measure the performance difference between two methods: find
and indexOf
on the Array prototype in JavaScript. The tests are run on different browsers (in this case, Firefox 105) to determine which method is faster.
What is being compared?
The test compares the execution speed of the following two methods:
Array.prototype.find(item => item == 1E5)
: This method returns the first element in the array that satisfies the condition. In this case, it's checking for an element with a value equal to 100,000 (1E5).Array.prototype.indexOf(1E5)
: This method returns the index of the first occurrence of the specified element.Pros and Cons
Here are some pros and cons of each approach:
find
:indexOf
:find
, as it uses a linear search algorithm with bounds checking.Library usage
In this benchmark, no external libraries are used. The Array.prototype.find
method is an ECMAScript Standardized Method (ESM), which means it's a built-in feature of the JavaScript language.
Special JS features or syntax
The benchmark uses a few special features:
const
and let
declarations for variable scope.item => item == 1E5
) for concise code.while
loop for creating an array with a large number of elements.No other special features are used in this benchmark.
Alternatives
If you wanted to measure the performance of these methods, you could use other approaches:
filter()
or a custom implementation using a binary search algorithm.Keep in mind that benchmarking can be complex, as it involves many factors like CPU architecture, memory management, and caching effects.