var arr = [];
var ms = new Map();
var i = 0;
while (i <= 1E5) {
arr[i] = i;
ms.set(i, i);
i++;
}
const item = arr.find(item => item == 1E5);
const index = arr.indexOf(1E5);
ms.has(1E5 - 1)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.find | |
Array.indexOf | |
dsds |
Test name | Executions per second |
---|---|
Array.find | 2002.4 Ops/sec |
Array.indexOf | 87336.4 Ops/sec |
dsds | 24850028.0 Ops/sec |
Let's break down the benchmark and its test cases.
Benchmark Overview
The benchmark measures the performance of three different ways to find an element in an array or a Map: find
, indexOf
, and direct key lookup using a Map (ms.has
).
Script Preparation Code
The script preparation code sets up two data structures:
arr
with 100,000 elements, initialized with values from 0 to 99,999.ms
with the same keys as arr
, but initialized with the same values.Individual Test Cases
There are three test cases:
const item = arr.find(item => item == 1E5);
find
method, which returns the first element in the array that satisfies the provided condition.find
method is a concise and expressive way to find an element in an array. It's also less prone to off-by-one errors compared to indexing-based approaches like indexOf
.item == 1E5
) to find the target element.const index = arr.indexOf(1E5);
indexOf
method, which returns the first index at which the specified value can be found in the array.indexOf
method is a well-established and widely supported way to find an element in an array. It's also relatively fast compared to iterating over all elements.arr.indexOf(1E5)
), which may not be as efficient as using a find
or map
method for large arrays.ms.has(1E5 - 1)
==
) may not be as efficient as other methods for finding matches in large arrays.has
method of the Map to check if a key exists. Note that this assumes that the keys are hashed and stored in an optimized format.Browser and Device Information
The benchmark result shows data from multiple browsers (Chrome 125 on Mac OS X 10.15.7) with different execution frequencies per second.
In summary, this benchmark measures the performance of three different methods for finding an element in a large array or Map: find
, indexOf
, and direct key lookup using a Map. The results provide insight into the relative efficiency of these approaches on modern browsers.