I decided to experiment with the performance of JavaScript Object
, Map
, and Set
when it comes to accessing keys. I tested the following three code snippets on JSBEN.CH.
Objects
const object = {};
for (let i = 0; i < 10000; ++i) {
object[`key_${i}`] = 1;
}
let result = 0;
for (let i = 0; i < 10000; ++i) {
result += object[`key_${i}`];
}
Maps
const map = new Map();
for (let i = 0; i < 10000; ++i) {
map.set(`key_${i}`, 1);
}
let result = 0;
for (let i = 0; i < 10000; ++i) {
result += map.get(`key_${i}`);
}
Sets
const set = new Set();
for (let i = 0; i < 10000; ++i) {
set.add(`key_${i}`);
}
let result = 0;
for (let i = 0; i < 10000; ++i) {
result += set.has(`key_${i}`);
}
Upon inspecting the results from the test link, it appears that while Map
and Set
display similar performance, Objects
consistently perform slower in comparison. What could be causing this discrepancy where Objects
are less efficient than Map
or Set
for basic key access operations?
Edit 1: Not only is accessing keys slower with Object
, but setting keys is also shown to be slower than with Map
or Set
.