var arr = Array.from({length: 1000000}).map((_,i) => ({id: i}));
var arrMap = new Map(arr.entries());
function idGen() {
return Math.floor(Math.random() * 1000000) % 1000000
}
const arrToMap = new Map(arr.entries());
const id = idGen()
arrToMap.get(id)
const id = idGen()
arr.find((item) => item.id ==id)
const id = idGen()
arrMap.get(id)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
array to map and find many | |
array find | |
map find |
Test name | Executions per second |
---|---|
array to map and find many | 6.0 Ops/sec |
array find | 155.0 Ops/sec |
map find | 1338361.9 Ops/sec |
Let's break down the provided benchmark definition and test cases.
Benchmark Definition
The benchmark definition is a JSON object that contains information about the test case, including its name, description, script preparation code, and HTML preparation code (which is empty in this case). The main difference between two approaches to find an element in an array:
idGen()
, retrieves a value from the map using that id (arrMap.get(id)
), and repeats this process for 1000000 iterations.Options Compared
The main options being compared here are:
arrMap.get(id)
), where the map's key is used as the id.Array.prototype.find()
method directly on the array, which searches for an element that matches the given condition.Pros and Cons
Here are some pros and cons of these different approaches:
Library
There is no library explicitly mentioned in this benchmark definition, however, Array.from()
and Map
are built-in JavaScript objects used here. However, some libraries like Lodash (_
) might provide optimized versions of these operations or offer additional functionalities that simplify your codebase:
import _ from 'lodash';
// Using _.find() for more complex condition checks
const result = _.find(arr, (item) => item.id === id);
Special JS Feature
In this benchmark definition, there are no special JavaScript features mentioned.