性能对比

概述

比较 普通创建的对象 和 反射创建的对象 ,调用方法哪个更快,相差多少

比较 反射调用方法,关闭和开启 安全权限检查 的性能

实例

/**
 * 通过反射创建对象 对比 普通创建对象 性能?
 */
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();
    }
}
原文地址:https://www.cnblogs.com/gbhh/p/13768186.html