var items = Array.from(Array(1000), (_,x) => ({key: x, value: x*10}));
var objContainer = new Map();
var arrContainer = [];
for (let i = 100; i >= 0; i--) {
const index = Math.floor(Math.random() * 1000);
const item = items[index];
objContainer.set(item.key,item);
arrContainer.push(item)
}
items.forEach(item => arrContainer.find(containerItem => containerItem.value === item.value))
items.forEach(item => objContainer.get(item.value))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array find | |
Map access |
Test name | Executions per second |
---|---|
Array find | 1234.4 Ops/sec |
Map access | 13112.9 Ops/sec |
Let's dive into the benchmark definition and results.
Benchmark Definition
The test case is called "Map key access vs array find". The goal of this benchmark is to compare the performance of accessing elements in two different data structures: JavaScript Maps (with keys) and arrays. The test case consists of two individual tests:
find()
method on an array (arrContainer
) to search for an element with a specific value.get()
method on a JavaScript Map (objContainer
) to retrieve an element by its key.Script Preparation Code
The script prepares two containers: objContainer
(a JavaScript Map) and arrContainer
(an array). It populates both containers with 1000 objects, each containing a key-value pair. The objects are generated randomly from the items
array.
Test Cases
There are two test cases:
items
array and for each item, it uses the find()
method on arrContainer
to search for an object with a value equal to the current item's value.items
array and for each item, it uses the get()
method on objContainer
to retrieve an object with a key equal to the current item's value.Latest Benchmark Results
The results show the execution time (Executions Per Second) of both tests on Chrome 123. The Map access test executes at approximately 13112 times per second, while the Array find test executes at around 1234 times per second.
Library Used
No external library is used in this benchmark.
JavaScript Features/Syntax Used
None specific to JavaScript features or syntax are mentioned in this benchmark.
Pros and Cons of Approaches
Other Alternatives
Other alternatives for accessing data in JavaScript include:
forEach()
method. While it's faster than an array for lookups, it's not designed for direct access by value.These alternatives should be considered based on the specific use case, performance requirements, and other factors such as scalability, maintainability, and development complexity.