<script src="lodash.js"></script>
var array = [Array(1000).keys()];
var map = new Map(array.map(a =>[a,a]));
var obj = Object.fromEntries(map);
for (let i = 0; i< 1000; i++ ){
map.get(i)
}
for (let i = 0; i< 1000; i++ ){
obj[i]
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
map | |
obj |
Test name | Executions per second |
---|---|
map | 12743.8 Ops/sec |
obj | 15838.3 Ops/sec |
I'd be happy to explain the provided benchmark and its test cases.
Benchmark Overview
The provided benchmark is designed to compare the performance of JavaScript Map
objects against Object
s when iterating over their entries. The benchmark measures the execution time for each approach, and the results are compared across different browsers and devices.
Script Preparation Code
The script preparation code creates an array of 1000 key-value pairs, converts it into a Map
object using Array.prototype.map()
to create arrays for each value, and then converts the Map
object to an Object
using Object.fromEntries()
. This setup is used as the base data structure for both test cases.
Html Preparation Code
The HTML preparation code includes a reference to the lodash.js
library, which is used in one of the test cases. Specifically, the "obj" test case relies on Lodash's _.at()
function to access the values in the object.
Test Cases
There are two test cases:
This test case measures the execution time for accessing a value using the get()
method of the Map
object, iterating 1000 times.
Example JavaScript code:
for (let i = 0; i < 1000; i++) {
map.get(i);
}
This test case measures the execution time for accessing a value using the square bracket notation ([]
) of the Object
, iterating 1000 times.
Example JavaScript code:
for (let i = 0; i < 1000; i++) {
obj[i];
}
Libraries and Special JS Features
Pros and Cons of Each Approach
Map
object using its key.Other Considerations
Map
object and Object
are populated with the same data structure (i.e., key-value pairs).Alternatives
Some alternative approaches could be explored:
Set
, which may perform better than a Map
object.I hope this explanation helps! Let me know if you have any further questions.