1. 程式人生 > 實用技巧 >效能對比

效能對比

概述

比較 普通建立的物件 和 反射建立的物件 ,呼叫方法哪個更快,相差多少

比較 反射呼叫方法,關閉和開啟 安全許可權檢查 的效能

例項

/**
 * 通過反射建立物件 對比 普通建立物件 效能?
 */
public class Demo05 {

//    普通方式
    public static void test(){
        User user = new User();
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 1000000000; i++) {
            user.getName();
        }
        long endTime = System.currentTimeMillis();
        System.out.println("普通方法,執行10億次:"+ (endTime - startTime) +"ms");
    }
//    反射方式
    public static void test1() throws Exception {
        User user = new User();
        Class c1 = user.getClass();
        long startTime = System.currentTimeMillis();
        Method getName = c1.getDeclaredMethod("getName", null);
        for (int i = 0; i < 1000000000; i++) {
            getName.invoke(user, null);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("反射方法,執行10億次:"+ (endTime - startTime) +"ms");
    }
//    反射方式 關閉安全許可權檢查
    public static void test2() throws Exception {
        User user = new User();
        Class c1 = user.getClass();
        long startTime = System.currentTimeMillis();
        Method getName = c1.getDeclaredMethod("getName", null);
        for (int i = 0; i < 1000000000; i++) {
            getName.setAccessible(true);
            getName.invoke(user, null);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("反射方法,關閉安全許可權檢查,執行10億次:"+ (endTime - startTime) +"ms");
    }

    public static void main(String[] args) throws Exception {
        test();
        test1();
        test2();
    }
}