Map vs Obj
by evgkch
JavaScript
const generateId = (elementLength = 4, blockLength = 4, notation = 16) => {
const generateElement = () => (Math.round(Math.random() * (notation - 1))).toString(notation);
const generateBlock = () =>
Array
.from({ length: elementLength }, (v) => generateElement())
.join('');
return Array
.from({ length: blockLength }, (v) => generateBlock())
.join('-');
};
const keysA = Array.from({ length: 100000 }, (v) => generateId());
const keysB = Array.from({ length: 100000 }, (v, k) => k);
const keysC = Array.from({ length: 100000 }, (v, k) => `${k}`);
const myMap = new Map;
const myObj = {};
console.log(addValues(myMap, keysA));
console.log(addValues(myObj, keysA));
console.log(addValues(myMap, keysB));
console.log(addValues(myObj, keysB));
console.log(addValues(myMap, keysC));
console.log(addValues(myObj, keysC));
console.log(getValues(myMap, keysA));
console.log(getValues(myObj, keysA));
console.log(getValues(myMap, keysB));
console.log(getValues(myObj, keysB));
console.log(getValues(myMap, keysC));
console.log(getValues(myObj, keysC));
function addValues(storage, keys){
const isMap = storage instanceof Map;
const keysLength = keys.length;
let i;
const start = performance.now();
for (i = 0; i < keysLength; i++){
if (isMap){
storage.set(keys[i], 1);
}else{
storage[keys[i]] = 1;
}
};
const time = performance.now() - start;
return { test: addValues.name, type: isMap ? 'Map' : 'Object', time, storage };
}
function getValues(storage, keys){
const isMap = storage instanceof Map;
keys = keys.sort(() => Math.random() > 0.5);
const keysLength = keys.length;
let i;
const start = performance.now();
for (i = 0; i < keysLength; i++){
if (isMap){
storage.get(keys[i]);
}else{
storage[keys[i]];
}
};
const time = performance.now() - start;
return { test: getValues.name, type: isMap ? 'Map' : 'Object', time, storage };
}