Item 5 in Effective Java Joshua Bloch says avoid creating your object pool unless the objects are extremely heavy weight but in jdk source I see IntergerCache in Integer class, LongCache and CharacterCache in Long and Character class.
public class autobox {
/**
* @param args
*/
public static void main(String[] args) {
long start=System.nanoTime();
Integer sum=0;
sum=sum+94; //1-- takes most time
long end=System.nanoTime();
System.out.println(end-start);
for(int i=0;i<1000;i++)
sum=sum+i;
end=System.nanoTime();
System.out.println(end-start); //--2
sum=0;
for(int j=5;j<1000;j++)
sum=sum+j;
end=System.nanoTime();
System.out.println(end-start); //--3
}
}
Output on my machine (with Java SE 1.7)
540686
984338
1450849
It looks like statement 1 is creating a too many objects all for the sake of creating just one Integer object!. I don't get the reason behind this. Though the documentation mentions -XX:AutoBoxCacheMax=<size>
I get an error Unrecognized VM option 'AutoBoxCacheMax=0'
.
Shouldn't the cache only keep created objects instead of creating unnecessary objects?