-1

I had an interview where the person asked me this question. Can anyone explains all the aspects so that i have a clear idea which structure to use when.

Aman Seth
  • 195
  • 1
  • 9

1 Answers1

0

Arrays:

  • Arrays provide order, Object's don't (at least not yet).
  • Arrays can be optimized (speed and even the memory footprint), when used as non sparse lists with items of the same type.
  • Arrays provide a bunch of functions to work with this data-structure

Objects:

  • Objects are more generic
  • Using the Object as a Dictionary: lookups are faster than iterating over an Array to find the right item.
    return itemsById[id]
  • Code for Objects with the same hidden class can also be optimized.

Conclusion:

Arrays: use them if you think of the data as a list; same type improves performance but ain't a requirement.
To be more precise: lists have no gaps (missing indices), the data may have gaps, but the list shouldn't. If the list would have gaps, then the index has a meaning beyond just order, and it's probably a Dictionary with numeric keys.

Dictionaries: Plain Object used as a dictionary for the advantage of the fast lookup. Mentioned separate, because it's a different state of mind, having/dealing with a dictionary of items and dealing with an Object composing some properties.

Objects: A composition of properties of "some object". Like the body parts of a person. Or the "row" in a table of data: {id, firstName, lastName, ...}
Avoid enumerated properties. If you have sth. like {foo1, foo2, foo3, ...} foo is most likely a list of whatever, and should be built as such (just makes your life easier).
unless this object is a dictionary

Thomas
  • 11,958
  • 1
  • 14
  • 23