DEV Community

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

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.)