天天看點

Integer的裝箱和拆箱(Boxing and unBoxing)的一個性能損失的例子另一個例子

package integerTest;

import java.util.Enumeration;
import java.util.Properties;

@SuppressWarnings("unused")
public class IntegerCompare {

    private static long start;
    private static void start(){
        start = System.currentTimeMillis();
    }
    
    public static void autoboxing(){
        Integer a = 10; 
        Integer b = Integer.valueOf(10);
    }
    private static long end(){
        return System.currentTimeMillis() - start;
    }
    
    private static final int NUM = 10000;
    private static int calc1(){
        Integer result = 0;
        for( Integer i = 0; i < NUM; i++){
            result += i;
        }
        return result;
    }
    
    private static int calc2(){
        int result = 0;
        for( int i = 0; i < NUM; i++){
            result += i;
        }
        return result;
    }
    
    public static void main(String[] args) {
        System.out.println("Calc1: " + calc1());
        System.out.println("Calc2: " + calc2());
        
        start();
        for( int i = 0; i < NUM; i++){
            calc1();
        }
        System.out.println("Calc1 time: " + end());
        
        start();
        for( int i = 0; i < NUM; i++){
            calc2();
        }
        System.out.println("Calc2 time: " + end());
        
        Properties properties = System.getProperties();
        
        int size = properties.size();
        System.out.println("Size: " + size);
        
        Enumeration<Object> keys =  properties.keys();
        
        int index = 0;
        while ( keys.hasMoreElements() ){
            Object obj = keys.nextElement();
            System.out.println();
            System.out.println("The [" + index + "] key: " + obj);
            index++;
            System.out.println("Value: " + properties.getProperty((String) obj) );
        }
    }
}
      

另一個例子

package performance;

public class LongTest {
    // 下面的代碼執行,在我們的機器上需要 9 秒,但當我把 Long 改成 long 之後,0 秒内就完成了)
    public static void main (String[] args) {
     long millis = System.currentTimeMillis ();
        Long sum = 0L; // uses Long, not long
        for (long i = 0; i <= Integer.MAX_VALUE; i++) {
            sum += i;
        }
        System.out.println (sum);
        System.out.println ((System.currentTimeMillis () - millis) / 1000);}
}      

繼續閱讀