Quote

"Between stimulus and response there is a space. In that space is our power to choose our response.
In our response lies our growth and freedom"


“The only way to discover the limits of the possible is to go beyond them into the impossible.”


Thursday 13 March 2014

Autoboxing and Unboxing Performance Impacts




Since JDK 1.5 autoboxing and unboxing have been introduced which helps in de-cluttering the code and taking care of necessary transformation automatically.

The NEED of Autoboxing and Unboxing:
Collections do not hold primitive values and can hold only object references. For example it cannot hold int instead it will need a wrapper like Integer to hold the corresponding integer values.  So the primitive int being put in a collection has to be boxed in Integer from int and the similarly it has to be unboxed to a primitive as the object coming out of the collection will be an Integer.

Implementation:

This transformation from primitive to wrapper and vice versa can be automatically handled since JDK 1.5.

 An example:
import java.util.*;

// Prints the count of the words
public class WordCount {
   public static void main(String[] args) {
      Map<String, Integer> countHolder = new TreeMap<String, Integer>();
      for (String word : args) {
          Integer count = countHolder.get(word);
          countHolder.put(word, (count == null ? 1 : count + 1));
      }
      System.out.println("The respective count of the words is:\n" + countHolder);
   }
}
As we know it is not possible to do a + 1 to an Integer, but we are able to do it in the case of ‘count’ which is declared Integer. This possible because of unboxing which makes it to primitive int and allows the ‘+1’ operation.

Impact:

Potential null pointer exception whenever the JDK tries to unbox null. This can be averted by using the == operator which does a reference identity comparison in Integer and value equality check on int.

Autoboxing and Unboxing operations also have performance implications. For a performance critical application autoboxing and unboxing should be avoided where it is being used in every get and set operation if possible. It should be used only when we have a mismatch between the reference types and primitives.

No comments:

Post a Comment