small array lookup vs small object lookup

Benchmark created on


Setup

const arr = [
  { name: 'Star Wars Episode 4', value: 'starWarsEpisode4' },
  { name: 'The Big Lebowski', value: 'theBigLebowski' },
  { name: 'Blade Runner', value: 'bladeRunner' },
  { name: 'Lady Bird', value: 'ladyBird' },
  { name: '500 Days Of Summer', value: '500DaysOfSummer' },
  { name: 'The Legend Of Zelda', value: 'theLegendOfZelda' },
  { name: 'Too Good To Be True', value: 'tooGoodToBeTrue' },
  { name: 'All We Know For Now', value: 'allWeKnowForNow' },
];

const obj = arr.reduce((acc, e) => {
  acc[e.value] = e.name;
  return acc;
}, {});

// create an array with 1000 randame values from the elements of arr
const lookup = Array.from(
  { length: 1000 },
  () => arr[Math.floor(Math.random() * arr.length)].value
);

const findInArray = (key) => {
  return arr.find((e) => e.value === key);
};

const findInObject = (key) => {
  return obj[key];
};

Test runner

Ready to run.

Testing in
TestOps/sec
Find in small array
for (let i = 0; i < lookup.length; i++) {
  findInArray(lookup[i]);
}
ready
Find in small object
for (let i = 0; i < lookup.length; i++) {
  findInObject(lookup[i]);
}
ready

Revisions

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