Initialize the wrapper types – Use Autoboxing or valueOf methods
Recently I had a debate with one of my colleague on whether or not to use autoboxing for initialization of Wrapper types in Java. I was in favor of explicit initialization but the issue of unnecessary object creation came up. I did a little search on it came to following conclusion:
1. The official documentation says use corresponding valueOf methods as this method is likely to yield significantly better space and time performance by caching frequently requested values.
2. When you use java.lang.Integer.valueOf its java.lang.Integer$IntegerCache class that controls the caching of integers. (Character class also has similar implementation).
3. Autoboxing or valueOf method will create new instance if used for java.lang.Double or java.lang.Float
I prefer using valueOf method.
To verify this I have written following code
/** * @author Dhananjay Kumar Jha * Copyright http://www.bataahmaithil.in * @Created 26 Aug 2012 */ public class AutoBoxingTest { private Double doubleAutoBox = 1D; private Double doubleValueOf = Double.valueOf(1D); private Integer integerAutoBox = 1; private Integer integerValueOf = Integer.valueOf(1); }
When decompiled version of the class were as follows
public class AutoBoxingTest { public AutoBoxingTest() { doubleAutoBox = Double.valueOf(1.0D); doubleValueOf = Double.valueOf(1.0D); integerAutoBox = Integer.valueOf(1); integerValueOf = Integer.valueOf(1); } private Double doubleAutoBox; private Double doubleValueOf; private Integer integerAutoBox; private Integer integerValueOf; }
The official Autoboxing documentation suggests not to use Autoboxing or Unboxing too frequently.
Leave a Reply