I was trying to explore how javascript Object
performs in comparison to Map
or Set
for normal key accesses.
So i ran the below 3 codes on JSBEN.CH (here is the link to test: https://jsben.ch/q4RPK)
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}`);
}
As you can check in the test link, map
and set
seem to perform almost similar however objects
are much slower every time. Can someone explain what could be the reason that objects
perform worse than map
or set
for basic key access operation?
Edit 1: As it turns out, just setting keys on objects
is also slower than map/set
: https://jsben.ch/al9ef