Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

will the speed of hashMap.get ("The String key") be affected by the size of the hashMap?

Tags:

java

hashmap

I am coming up a very bold idea. That is I want to use a HashMap instead of Database to store data for a Chat App.

So, when the user send a chat message, the chat message of that particular user will be stored into a HashMap using storeMsg().

Each user will have a separated chat room. Every 5 seconds, the chat room of that particular user will send a getMsg() method to retrieve the latest message inside that chat room. After it retrieve the message, it will remove all the messages relating to that chat room of that particular user so that we can avoid the overhead.

So, only users exist in that chat room can see the messages, the message can be just appended one by one. The new users who enter that chat room lately will not be able to see the previous messages. This is similar to peer to peer Chat.

Each user has a unique String username such as "tomhan12", "Mary2","123cat", etc.

public void storeMsg(String userName, String message){
   hMap.put(userName, message);
}

public String getMsg(String userName){
    return hMap.get(userName);
}

So, my question is that if the hMap has Keys that are Strings & if that hMap has like millions of entries, then will speed of hMap.get(str) be affected?

Can we convert the String userName into a unique integer number & then "hMap.put(thatUniqueIntegerNumber, message)" for higher performance? or the HashMap did that for us so we don't need to do that?

like image 614
Tum Avatar asked Dec 27 '25 16:12

Tum


1 Answers

HashMap's get has an expected constant running time, which means its running time shouldn't depend on the size of the HashMap. This, of course, relies on a decent implementation of the hashCode method of your key, but your key is String, so it shouldn't be a problem.

That said, using a large HashMap (or any other large data structure) consumes a large amount of memory, so you should pay attention that you are not running into lack of memory issues, which would slow down your application.

like image 76
Eran Avatar answered Dec 30 '25 05:12

Eran