-1

Are there any disadvantages (in terms of memory) for using Maps in Java?

Because as per my knowledge if you are using HashMaps or any other collections Classes .

For eg.

Map<String , String> map = new HashMap<String, String>();

map.put("id",1);
map.put("name","test123");

So I used 2 bites for each one of those let's assume. And according to me Map or any other collection hold 100 bites so remaining 98 bites are wasted. So, for that scenario, can I use anything else?

abarisone
  • 3,707
  • 11
  • 35
  • 54

2 Answers2

2

For a description of initial capacity and load factor, see What is the significance of load factor in HashMap?

If you use arrays, you will probably use less memory than when you use a map. But in most cases, the ease of use and readabilty is far more important than memory usage.

See also Hash Map Memory Overhead for a description of HashMaps memory usage.

Community
  • 1
  • 1
user140547
  • 7,750
  • 3
  • 28
  • 80
1

First of all, yes, creating a map has some memory overhead for very small amounts of data. It creates arrays with Entry wrapper classes for the given load capacity/load factor. So, you might be wasting a few bytes, but in the age of gigabyte-sized memory, that would only become an issue when you would be creating millions or even billions of maps, depending on how much memory you actually give your application and what other things it has to manage.

If I know that a collecting will remain really small and I'm not using the keys anyway, I sometimes just use a list instead, because checking 2 or 4 elements is quite fast anyway. In the end, do not even bother to worry about such minor things until they are taking up a major slice of available memory.

Silverclaw
  • 1,316
  • 2
  • 15
  • 28