JavaScript object vs. array lookup performance

This problem touches all programming languages. It depends on many factors:

  • size of your collection -arrays will get slower when you are searching for the last key, and array is quite long
  • can elements repeat them selves-if yes, than you need a array. If no: you need either a dictionary (map) or you need to write a add method that for each add will iterate your array and find possible duplicates-that can be troublesome, when dealing with large lists
  • average key usage - you will lose performance, if the most requested userId is at the end of the list.

In your example map would be a better solution. Secondly, you need to add a break to yor code:)

var user;

for (var i = 0; i < users.length; i ++) {
  if (users[i].id == id) {
     user = users[i]; break;
  }
}

Or you will lose performance:)


The answer to this is browser dependent, however, there are a few performance tests on jsperf.com on this matter. It also comes down to the size of your data. Generally it is faster to use object key value pairs when you have large amounts of data. For small datasets, arrays can be faster.

Array search will have different performance dependent on where in the array your target item exist. Object search will have a more consistent search performance as keys doesn't have a specific order.

Also looping through arrays are faster than looping through keys, so if you plan on doing operations on all items, it can be wise to put them in an array. In some of my project I do both, since I need to do bulk operations and fast lookup from identifiers.

A test:

http://jsben.ch/#/Y9jDP

Tags:

Javascript