const map = new Map();
const obj = {};
const count = 1000
const l = []
for (let x=0; x<=count; x++) {
l.push([[''+x, x]])
}
function bMap() {
'use strict'
for (let j = 0; i+j < count; j++){
for (let i = 0; i < count; i++) {
const [k, v] = l[i]
if (!map.has(k)) {
map.set(k, v)
} else {
map.set(k, map.get(k)+j)
}
}
}
}
function bObj() {
'use strict'
for (let j = 0; i+j < count; j++){
for (let i = 0; i < count; i++) {
const [k, v] = l[i]
if (!obj.hasOwnProperty(k)) {
obj[k] = v
} else {
obj[k] = obj[k]+j
}
}
}
}
bMap()
bObj()
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Map lookup | |
Obj lookup |
Test name | Executions per second |
---|---|
Map lookup | 7.2 Ops/sec |
Obj lookup | 0.3 Ops/sec |
I'll break down the provided benchmark and explain what's being tested, the options compared, their pros and cons, and other considerations.
Benchmark Overview
The MeasureThat.net benchmark tests the performance of two data structures in JavaScript: Maps (or Maps) and Objects. The test creates a large dataset of key-value pairs, then uses these data structures to perform lookups.
Script Preparation Code
The script preparation code is identical for both data structures:
const map = new Map();
const obj = {};
const count = 1000;
const l = [];
for (let x=0; x<=count; x++) {
l.push([[''+x, x]]);
}
This code creates a large array l
with key-value pairs, where each key is a string and the value is the corresponding number. It also initializes an empty Map (map
) and Object (obj
).
Benchmark Functions
There are two benchmark functions:
function bMap() {
'use strict'
for (let j = 0; i+j < count; j++) {
for (let i = 0; i < count; i++) {
const [k, v] = l[i]
if (!map.has(k)) {
map.set(k, v)
} else {
map.set(k, map.get(k)+j)
}
}
}
}
This function iterates through the array l
and for each key-value pair, it checks if the key is present in the Map. If not, it sets the value in the Map. If the key is already present, it increments the existing value by a fixed amount (j
) added to the previous value.
function bObj() {
'use strict'
for (let j = 0; i+j < count; j++) {
for (let i = 0; i < count; i++) {
const [k, v] = l[i]
if (!obj.hasOwnProperty(k)) {
obj[k] = v
} else {
obj[k] = obj[k]+j
}
}
}
}
This function is similar to bMap()
, but it uses the Object data structure instead. It checks for the presence of each key in the Object using the hasOwnProperty()
method, and increments the value if present.
Options Compared
The two benchmark functions compare the performance of:
Pros and Cons
Here are some pros and cons of each approach:
Other Considerations
bMap()
nor bObj()
uses any external libraries.Alternatives
If you're interested in exploring alternative data structures, here are some options:
Keep in mind that the choice of data structure ultimately depends on your specific use case and requirements.