code đờ
code đờ

Reputation: 615

Java HashMap.remove(key) VS HashMap.put(key,null) - Which is faster?

I wonder if HashMap.put(key,null) has better performance over HashMap.remove(key) or not ?

Upvotes: 0

Views: 1529

Answers (3)

David D. Li
David D. Li

Reputation: 1

On top of @Slaw's comment, if you use HashMap.put(key,null) in lieu of HashMap.remove(key), the size of the map would not change. This could cause unintended side effects.

    Map<String, String> test = new HashMap<>();
    System.out.println("Size: " + test.size());  // Size: 0

    test.put("John", null);
    System.out.println("Size: " + test.size());  // Size: 1

Upvotes: 0

Laiba Ijaz Khan
Laiba Ijaz Khan

Reputation: 115

It depends on which approach you use in your code. HashMap.put(key,null) is different from HashMap.remove(key) as put is used for adding some value and remove is used for removing. The time complexity of HasMap is O(1). As both are used in HashMap so their time Complexity will be same.So i think they both are faster.

Upvotes: 1

wWw
wWw

Reputation: 192

Which one is better totally depends on how you use your HashMap in your code since they are two different methods doing two different things.

If you are only considering performance and if you are merely curious about which one is faster, there would be no big difference since HashMap has time complexity of O(1) for both put and remove.

I am guessing there might be a small performance benefit for remove since it reduces the total number of keys in HashMap and it is definitely possible for HashMap to have time complexity of O(n) in the worst case, but I think it is negligible.

Upvotes: 0

Related Questions