May 18, 2010

Java Code Optimization: Tip # 1: How To Use Java Map .contains() and .get()

One very common mistake that I see in application code written in java is the way maps are accessed! Though it is very common, in my opinion I would say that this is an expensive mistake! Go ahead, get to know what the error literally is and correct the same if you come across one in future for that would help you to have an optimized code on the fly.

Let us say that we have a map! Let us create the map
Map<Integer,String> testMap = new HashMap<Integer, String>();
testMap.put(1,"one");
testMap.put(2,"two");

Here, while looping through the keyset of the above Hashmap, a java developer very often tries to do the following:

Un-Optimized Code:
<br />if(testMap.contains(1))<br />{<br />    String tempString = testMap.get(1);<br />    System.out.println(tempString);<br />}<br />

This is emphatically a stress to the memory and makes an un-optimized code. Here,
  • We check whether the map contains the key we are looking for.
  • Next, we try to get the value of the key if the key is present in the map
  • We access the map 2 times and if this is placed within a for loop, imagine the number of times we would be accessing the map

The above code can easily be replaced by:

Optimized Code:
<br />String tempString = testMap.get(1);<br />if( tempString == null)<br />{<br />    System.out.println(tempString);<br />}<br />

In the optimized code,
  • we are not checking whether the map contains the key we are looking for.
  • We are just trying to get the value for the key specified.
  • If the key exists in the map, we would have a valid value in the tempString.
  • Else, this would be null and hence we access the map just once for every check we do!

In my opinion, rather than accessing map.contains() and map.get() for every check, trying to get the value by using map.get() would render an optimized code
That was one optimization technique that I found was really utile! And hence thought of sharing the same with you all!

No comments:

Post a Comment