1

In my Android app, I am using Firebase Database to store the data. There are some values that I want to store in the Firebase Database as a Map<String, Integer>.

When retrieving my data for display on the Android UI, I mostly need data "sorted by key".

My question is from a performance viewpoint whether I should declare the Map as a Hashmap or a Treemap? For e.g. like

Map<String, Integer> myData = new Hashmap<>();

or

Map<String, Integer> myData = new Treemap<>();

Of the above 2 options, which would give me a better performance for retrieval of data. Each Map size is expected to be in range of 0 to 10,000 entries. And there could be anywhere between 5-11 such Maps in my database for each user.

My question is specifically to target understanding performance of Firebase and not a general question about the difference between 2 map types.

Abhishek
  • 1,261
  • 1
  • 13
  • 30

1 Answers1

1

Both classes, Hashmap and Treemap implement the Map interface. Both classes offer mostly the same functionality but the most important difference between this classes is the order in which iteration through the entries will happen.

  • HashMap offers no guarantees about the iteration order and it can also change completely when new elements are added/deleted. Lookup-array structure, based on hashCode(), equals() implementations, O(1) runtime complexity for inserting and searching, unsorted.

  • TreeMap will iterate according to the natural ordering of the containing keys according to their compareTo() method. This can also be accomplished with an external Comparator. It also implements the SortedMap interface. Tree structure, based on compareTo() implementation, O(log(N)) runtime complexity for inserting and searching, sorted.

Use a HashMap unless you have some need for ordering. HashMap is faster!. But as you said that you mostly need your data "sorted by key", just use the TreeMap.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193