Impact on the performance of retrieving an item from a list

advertisements

In my Code I maintain a data heap whose basic component is a Map.The Map would be somewhat like:

Key -TableName\Field\Attribute1
Value-3

I used to retrieve my value by :

map.get(key)

Now I required a List instead value.The Map would be somewhat like:

Key -TableName\Field\Attribute1
Value-[3,30,300]

Now I need to retrieve my value by :

map.get(key).get(index)

How much would this change affect the performance of my Code?


I don't think there exist single answer to your question, its broad and you can consider all the answers. Basically, you need to understand time complexity of HashMap and ArrayList and that would give you an idea on how your code is going to perform.

The following image (source) gives you an idea of time complexity O(1), O(log n), O(n), ...

Now Hashmap have the following time complexity (see here for more details on how hash map work in java)

get() and put() - usually O(1) but O(n) worst case scenario

Best case scenario, get() and put() have O(1) cost in time complexity. If you have a inefficient hash function then the data is not distributed correctly across buckets hence, you might end with slow get() and put() methods. An efficient hash function distributes the data in all buckets in a balanced manner, if there is no balance between the buckets containing entries then you will have slower get() and put(). See here and here for details on how to design your hash function.

Note the HashMap performance improvement in Java 8.

ArrayList on the other hand have the following time complexity:

add() - O(1)
remove() - O(n)
get() - O(1)
contains() - O(n) (traversal)

Basically you perform O(1) (O (n) worst case) to get the list and then you are doing another O(1) to get the item from list. So both operations are in constant time provided your hash function is efficient.

As mentioned in other answers, there are a variety of other ways to improve the performance of your code by using array instead of list if possible, and so on.