DEV Community

Discussion on: JS Performance: Perhaps We Shouldn't Always Use Arrays

Collapse
 
nimmo profile image
Nimmo

Even in JS I wouldn't automatically reach for maps to be honest, as arrays are arguably easier for people to reason about and have so many useful methods on their prototypes (and um, I only found out that Map exists in JS last night...), but the thing that sparked this blog post was a real-world scenario that caused something at work to literally not work (due to AWS Lambda timing out) thanks to the poor performance of array.find on a massive array of things!

So definitely something to keep in mind if you know you'll be trying to find a cat in 10,000 cats, but yeah, I hear you re: not defaulting to them in other languages (and would go so far as to say that I wouldn't default to them in JS either - although I didn't know that about arrays being hash tables, so thanks for the extra info there! :) ).

Collapse
 
cdhowie profile image
Chris Howie • Edited

To clarify, when I refer to maps, I am primarily referring to objects, not instances of Map. Native JS objects are usable as maps, when the keys are strings (or can be unambiguously represented as strings).

The place you have to be careful is if you are already receiving an array from some API and you need to look up one item -- converting that array to some kind of map to look up a single item is going to cost more time than performing a linear search of the array. However, if your code is responsible for building the array in the first place, changing it to build an object should have the same performance while allowing O(1) lookups by key.

Re arrays having useful methods on their prototypes: yes -- though .find in particular is usually useless since you already have a way to look up items by key. (If you need the other prototype methods, there is Object.values(), though this does create an intermediate array which can impact performance.)