Saturday, February 12, 2005

Efficiency of Autoboxing in Java

I am trying to catch up with the changes in J2SE5.0. One of the feature additions is auto-boxing and auto-unboxing. It's a great feature and simplifies programming, reduces errors, but as well noted it is not efficient. Over use will result in a performance hit. Please see autoboxing notes from SUN for more details. I tried some experiments myself and found that auto-boxing happens each time, no caching is done for auto-boxed or auto-unboxed values. Below is a program and its disassembled output





public class AB4 {
public static void main(String args[])
{
Integer j = new Integer(1000);
int i = j + j + j + j;
int k = j + j;
System.out.println("i is " + i);
System.out.println("j is " + j);
System.out.println("k is " + k);
}
}


Compiled from "AB4.java"
public class AB4 extends java.lang.Object{
public AB4();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."":()V
4: return

public static void main(java.lang.String[]);
Code:
0: new #2; //class java/lang/Integer
3: dup
4: sipush 1000
7: invokespecial #3; //Method java/lang/Integer."":(I)V
10: astore_1
11: aload_1
12: invokevirtual #4; //Method java/lang/Integer.intValue:()I
15: aload_1
16: invokevirtual #4; //Method java/lang/Integer.intValue:()I
19: iadd
20: aload_1
21: invokevirtual #4; //Method java/lang/Integer.intValue:()I
24: iadd
25: aload_1
26: invokevirtual #4; //Method java/lang/Integer.intValue:()I
29: iadd
30: istore_2
31: aload_1
32: invokevirtual #4; //Method java/lang/Integer.intValue:()I
35: aload_1
36: invokevirtual #4; //Method java/lang/Integer.intValue:()I
39: iadd
40: istore_3



As can be seen, for each occurrence of j, the value is auto-unboxed and then added, could these values not be cached? Maybe, I need to specify a higher level of optimization, but at first glance I could not find specification of the level of optimization.
Post a Comment