RangerReturn
RangerReturn

Reputation: 171

Performance benefits of using a List vs Map in Java

I have been wondering what is the actual benefit of using Lists. Please note that my question is not "when to use what" but rather Is there any impact on performance if i insist on having maps as my primary objects

obviously if my aim is to just work on values

UPDATE after not being clear with my intent at first glance: I meant if i just want to filter a list of [8000] people whose age is > 30 , i would use a list... But can i use a map instead and have it be used instead - My Question is - will there be any performance hindrance ?

I would also use List. But do we get any performance boost - if yes - How can I see it myself.

for example if i take

List <Integer> listOfInt = new ArrayList<>(map.values());

It would make sense to use Map as my global object and serve lists based on it.

I know the key/value O(1) runtime for insert or remove in Maps but then why Lists are preferred most places i have seen.

Upvotes: 2

Views: 16083

Answers (2)

gusto2
gusto2

Reputation: 12087

my question is not "when to use what"

but it should. List and Map are having different use. A List is - well - a list of values without any explicit key. Item in a list is designated by its position.

obviously if my aim is to just work on values I would also use List.

yes, that's correct

But do we get any performance boost

Please note,. the Map is not a simple structure. For each item in a map, an "Entry" object is created with references to the key and the value object, an hash array is created, etc.. so using map you definitely use more memory and code. For simpler cases the performance difference is negligible

Upvotes: 9

Murat Karag&#246;z
Murat Karag&#246;z

Reputation: 37624

It depends on the use case. With your example it could make a difference in the usage for example if you want access a specific object. The access time with a List would be O(n) while in a Map it is O(1).

If you don't care about specific retrieval of objects you can use a List.

Upvotes: 1

Related Questions