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!