Autoboxing, unboxing and performance issues in Java

In Java, autoboxing and unboxing are great features.  Autoboxing simply converts the primitive type into wrapper type silently. Here is the simple example about autoboxing

 

class AutoboxingExample
{
   public static void myMethod(Integer num){
	System.out.println(num);
   }
   public static void main(String[] args) {
       /* passed int (primitive type), it would be 
        * converted to Integer object at Runtime
        */
   	myMethod(7);
   }
}

Unboxing is opposite of autoboxing. Integer object converted to primitive type automatically

 

class UnboxingExample
{
   public static void myMethod(int num){
	System.out.println(num);
   }
   public static void main(String[] args) {
    	
    	Integer integerObject = new Integer(200);
    	
        /* passed Integer wrapper class object, it 
         * would be converted to int primitive type 
         * at Runtime
         */
    	myMethod(integerObject);
    }
}

In Toplam class sum reference is Long wrapper type so Java is doing its magic

public class Toplam {


	public static void main(String[] args) {
		Long sum = 0L;
		long start = System.currentTimeMillis();
		for (long i = 0; i < Integer.MAX_VALUE; i++) {
			sum += i;
		}

		System.out.println( System.currentTimeMillis() - start);
		System.out.println(sum);

	}
}

 

In the for loop,  primitive “i” reference (long) is going to be converted to the Long object and this will cause performance problems.

public class Toplam {


	public static void main(String[] args) {
		long sum = 0L;
		long start = System.currentTimeMillis();
		for (long i = 0; i < Integer.MAX_VALUE; i++) {
			sum += i;
		}

		System.out.println( System.currentTimeMillis() - start);
		System.out.println(sum);

	}
}

If you run above program you will see the performance gain because there will be no autoboxing.

No Comments

Post a Comment

Comment
Name
Email
Website