DEV Community

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

Collapse
 
kepta profile image
Kushan Joshi • Edited

Most of the times choosing the right data structure is crucial to ones application. Maps and Arrays both have places where one is favoured over the other.

For Map

  • I choose map when I want to iterate over a collection and also want to look up directly using a unique ID. It sorta works like a regular object, with added powers of being able to iterate efficiently and keys can be of any data type.
  • Maps are much more efficient when you have to do a lot of read and writes. Last I read, an array with holes (deleting values in between) gets deoptimized into an object.

For Array

  • Maps even though good at iteration, can never be faster than a plain array when it comes to iteration.
  • Arrays are great when you want a data structure which has a continuous range of number indices. For eg array[4]; or array[10000].
  • With arrays you get loads of functional helper methods (.map, .reduce, .every, .some, .reduce, etc), but with Map you do not! If you find yourself implementing them, you should rethink about using Map in the first place.
  • Arrays are great when you have a one to many data structure. In your example what if there are 2 or more Aeries?
  • Maps and other complex data structure are hard to JSON.stringify (serialise). To serialise them, you end up converting them into an array of tuples. If you frequently have to serialise your data structure, you should be careful before using Maps.
  • Maps do not play well when you want to enforce immutability as the native API is not really written keeping immutability in mind. But with Arrays you can use Object.freeze or use .concat. If you want your data structure to be a Map (dictionary), Immutable.js is a good place to look at.
Collapse
 
nimmo profile image
Nimmo

You should make this into a post in itself - this is great advice. <3