Object vs Map

Benchmark created on


Setup

const randInt = () => Math.floor(Math.random() * 1_000_000);

const numbers = Array.from({ length: 1000 }, randInt);

const numberObject = {};
numbers.forEach((number) => { numberObject[number] = randInt() })

const numberMap = new Map();
numbers.forEach((number) => { numberMap.set(number, randInt()) })

const strings = numbers.map((number) => `key${number}`);

const stringObject = {};
strings.forEach((string) => { stringObject[string] = randInt() });

const stringMap = new Map();
strings.forEach((string) => { stringMap.set(string, randInt()) });

// shuffle arrays
for (let i = numbers.length - 1; i > 0; i--) {
  const j = Math.floor(Math.random() * (i + 1));
  [numbers[i], numbers[j]] = [numbers[j], numbers[i]];
  [strings[i], strings[j]] = [strings[j], strings[i]];
}

Test runner

Ready to run.

Testing in
TestOps/sec
Object with numbers
let x = 0;
numbers.forEach((number) => {
  x += numberObject[number];
});
ready
Map with numbers
let x = 0;
numbers.forEach((number) => {
  x += numberMap.get(number);
});
ready
Object with strings
let x = 0;
strings.forEach((string) => {
  x += stringObject[string];
});
ready
Map with strings
let x = 0;
strings.forEach((string) => {
  x += stringMap.get(string);
});
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.