const randomMax = 100000000
const objectPoolSize = 100
const objectsToFind = 10
const getRandomNumber = (max) => {
return Math.floor(Math.random() * max);
}
class TestObject {
constructor() {
this.a = getRandomNumber(randomMax)
this.b = 'Test String'
}
}
var map = new Map()
var array = []
for (let i = 0; i < objectPoolSize; i++) {
const testObject = new TestObject()
map.set(testObject.a, testObject)
array.push(testObject)
}
var objectIdsToFind = [];
for (let i = 0; i < objectsToFind; i++) {
objectIdsToFind.push(array[getRandomNumber(array.length)].a)
}
for (let i = 0; i < objectIdsToFind.length; i++) {
array.find((val) => val.a === objectIdsToFind[i])
}
for (let i = 0; i < objectIdsToFind.length; i++) {
map.get(objectIdsToFind[i])
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.find | |
Map.get |
Test name | Executions per second |
---|---|
Array.find | 1723915.9 Ops/sec |
Map.get | 124503136.0 Ops/sec |
Let's break down the provided benchmark and its test cases.
Benchmark Overview
The benchmark compares the performance of two approaches: array.find
versus map.get
. The goal is to find an element in a pool of 100 objects (represented by the TestObject
class) using either an array or a map. The pool consists of objects with unique identifiers (a
) and a string property (b
).
Script Preparation Code
The script preparation code generates:
getRandomNumber
) to create random numbers between 0 and randomMax
.TestObject
class with a constructor that sets the object's properties, including a unique identifier (a
) and a string property (b
).array
) and a map (map
) initialized with the generated objects.objectIdsToFind
).Individual Test Cases
There are two test cases:
The Array.find
test case uses the following code:
for (let i = 0; i < objectIdsToFind.length; i++) {
array.find((val) => val.a === objectIdsToFind[i])
}
This code iterates over the objectIdsToFind
array and for each identifier, it uses the find
method on the array
to find an element with a matching a
property.
The Map.get
test case uses the following code:
for (let i = 0; i < objectIdsToFind.length; i++) {
map.get(objectIdsToFind[i])
}
This code iterates over the objectIdsToFind
array and for each identifier, it uses the get
method on the map
to retrieve an object with a matching a
property.
Pros and Cons
Map.get
since it doesn't require extra memory allocation.Array.find
.Library and Special JS Features
The benchmark uses the following JavaScript features:
TestObject
) using the class
keyword.(val) => val.a === objectIdsToFind[i]
) in the Array.find
test case.These features are part of modern JavaScript and are supported by most browsers.
Alternatives
Other alternatives for implementing this benchmark could be:
Array.find
and Map.get
.However, the benchmark's focus on comparing array.find
and map.get
, two built-in methods in JavaScript, makes it a relevant test case for understanding the performance trade-offs between these two approaches.