JS Performance: Perhaps We Shouldn't Always Use Arrays

nimmo

Nimmo

Posted on July 26, 2018

JS Performance: Perhaps We Shouldn't Always Use Arrays

It feels like I spend quite a lot of time trying to find things that are in arrays. Almost as much time as I spend trying to locate my cats!

Consider the following:

const catsArray = 
  [ {name: 'Aeris', isFavourite: true}
  , {name: 'Juri'}
  , {name: 'Dante'}
  , {name: 'Frankenstein'}
  ];

const findMyCat =
  requestedCat =>
    catsArray.find(({name}) => name === requestedCat);

findMyCat('Dante'); // {name: 'Dante'}
findMyCat('Marmalade'); // undefined
Enter fullscreen mode Exit fullscreen mode

I want to find Dante (which is a common real-world problem), and to do so I first need to check to make sure that Aeris isn't Dante, and then I have to check that Juri isn't Dante either. A bit weird, but okay. And if I want to check to see if I have a cat called Marmalade, I have to check all of my cats first, just to be sure I don't. Hm.

Perhaps my data could be represented a bit better here?

const catsMap = new Map(
  [ ['Aeris', { name: 'Aeris', isFavourite: true }]
  , ['Juri', { name: 'Juri' }]
  , ['Dante', { name: 'Dante' }]
  , ['Frankenstein', { name: 'Frankenstein' }]
  , ['Aeris', { name: 'Aeris' }]
  ]
)

const findMyCat =
    requestedCat => catsMap.get(requestedCat)

findMyCat('Dante'); // {name: 'Dante'}
findMyCat('Marmalade'); // undefined
Enter fullscreen mode Exit fullscreen mode

Now the next time I want to find Dante, I can just look for him. If he's there at catsMap['Dante'] like he's supposed to be, I'll find him, and if he's not, I won't - but I won't need to waste my time looking at any other cats along the way. Imagine the difference this will make when I have 10,000 cats, none of which are called Marmalade; I just saved myself 10,000 (hypothetical) operations!

Update:

I knew that if I posted this message here, someone would quickly offer up a better alternative, so thank you to Weston Wedding for pointing out that Maps actually exist in JS now! (I've updated the example in this post to reflect this, so if you're reading this for the first time you don't need to worry about the "old" one :) )

Also thanks to Oscar for the following performance test, showing the difference between the two approaches described in the original post. <3

💖 💪 🙅 🚩
nimmo
Nimmo

Posted on July 26, 2018

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related