Skip to content

Instantly share code, notes, and snippets.

@devlato
Created September 26, 2023 02:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devlato/9a3040019264cff448ca4f4fa73fbbc6 to your computer and use it in GitHub Desktop.
Save devlato/9a3040019264cff448ca4f4fa73fbbc6 to your computer and use it in GitHub Desktop.
Map vs obj read benchmark
async function checkAvgPerf() {
const numberOfReads = 100000;
const numberOfTests = 100;
const eps = 0.000001;
const mapAvg = [];
const objAvg = [];
let mapSlowerOnAvgTimes = 0;
let objSlowerOnAvgTimes = 0;
let equalTimes = 0;
function sum(arr) {
return arr.reduce((acc, v) => acc + v, 0);
}
async function checkReadPerf() {
return new Promise((resolve, reject) => {
setTimeout(
() => {
try {
const key = 'a';
const value = 100;
const map = new Map();
map.set('a', 100);
const obj = {};
obj['a'] = 100;
const readValueFromMap = () => map.get('a');
const readValueFromObj = () => obj['a'];
let mapTimes = 0;
let objTimes = 0;
for (let i = 0; i < numberOfReads; i++) {
const startTime = performance.now();
readValueFromMap();
const mapTime = performance.now();
readValueFromObj();
const objTime = performance.now();
mapTimes += mapTime - startTime;
objTimes += objTime - mapTime;
}
const mapTimesAvg = mapTimes / numberOfReads;
const objTimesAvg = objTimes / numberOfReads;
resolve({
mapTimesAvg,
objTimesAvg,
slowerOnAvg:
mapTimesAvg - objTimesAvg > eps
? 'map'
: objTimesAvg - mapTimesAvg > eps
? 'obj'
: 'equal',
});
} catch (e) {
reject(e);
}
},
Math.floor(Math.random() * 5),
);
});
}
for (let i = 0; i < numberOfTests; i++) {
const results = await checkReadPerf();
mapAvg.push(results.mapTimesAvg);
objAvg.push(results.objTimesAvg);
if (results.slowerOnAvg === 'map') {
mapSlowerOnAvgTimes++;
} else if (results.slowerOnAvg === 'obj') {
objSlowerOnAvgTimes++;
} else if (results.slowerOnAvg === 'equal') {
equalTimes++;
} else {
throw new Error(`Unexpected result "${results.slowerOnAvg}"`);
}
}
if (mapSlowerOnAvgTimes > objSlowerOnAvgTimes) {
console.log(
`Map is slower in most tests after ${numberOfTests} tests and ${numberOfReads} reads each (${mapSlowerOnAvgTimes} vs ${objSlowerOnAvgTimes} tests, eps=${eps})`,
);
} else if (mapSlowerOnAvgTimes < objSlowerOnAvgTimes) {
console.log(
`Obj is slower in most tests after ${numberOfTests} tests and ${numberOfReads} reads each (${mapSlowerOnAvgTimes} vs ${objSlowerOnAvgTimes} tests, eps=${eps})`,
);
} else {
console.log(
`Map and obj have equal read times in most tests after ${numberOfTests} tests and ${numberOfReads} reads each (${mapSlowerOnAvgTimes} vs ${objSlowerOnAvgTimes} tests, eps=${eps})`,
);
}
console.log(
`Map average read time is ${sum(mapAvg) / numberOfTests}`,
);
console.log(
`Obj average read time is ${sum(objAvg) / numberOfTests}`,
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment