Showing posts with label collection. Show all posts
Showing posts with label collection. Show all posts

Monday, March 6, 2017

[Performance] java Map.containsKey() redundant when using map.get()


In most of our code, we generally use HashMap.

 

Most of the operation we do:

·         Prepare HashMap to process.

·         Process the HashMap.

·         Retrieve data from Map.

 

Following use-case needs to be avoided:

Most of the time to avoid NPE (NullPointerException) code is getting handled in below way:

 

 

 

          dataMap.contains(key) ? dataMap.get(key) : someObject;

 

 

Avoid using above as it may impact performance because both below APIs do same operation:

·         containsKey()

·         get(key)

 

SO optimized code for avoiding redundant Map processing:

 

 

  Object  mappedValue = dataMap.get(key);       // fetch only once

 (mappedValue == null) ? someObject: mappedValue;

 

 

 

This is definitely useful for dealing bigger DataSet.

 

Also don't forget to use collection.clear(); if data is no more required.

 

 

III

Best Regards,

Abhjeet.