十二、性能对比

1.普通方式

2.反射但不关闭安全检查的方式方式

3.反射并关闭安全检查的方式

 

public class Demo09 {

    public static void main(String[] args) throws ClassNotFoundException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {

        test01();
        test02();
        test03();
    }


    //普通方式调用
    static void test01(){
        long start = System.currentTimeMillis();

        User user = new User();

        for (int i = 0; i < 100000000; i++) {
         user.getName();
        }


        long end = System.currentTimeMillis();
        System.out.println("普通方式耗时:"+(end-start));

    }

    //反射调用
    static void test02() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        long start = System.currentTimeMillis();

        Class clazz = Class.forName("com.zx.reflection.User");
        User user = (User) clazz.newInstance();
        Method getName = clazz.getMethod("getName", null);


        for (int i = 0; i < 100000000; i++) {
            getName.invoke(user);
        }
        long end = System.currentTimeMillis();
        System.out.println("反射不关闭安检方式耗时:"+(end-start));

    }

    //反射调用并关闭安全检查
    static void test03() throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        long start = System.currentTimeMillis();

        Class clazz = Class.forName("com.zx.reflection.User");
        User user = (User) clazz.newInstance();
        Method getName = clazz.getMethod("getName", null);

        getName.setAccessible(true);
        for (int i = 0; i < 100000000; i++) {
            getName.invoke(user);
        }
        long end = System.currentTimeMillis();
        System.out.println("反射并关闭安检方式耗时:"+(end-start));
    }

}

结果如下:

posted @ 2022-06-12 02:03  Epiphany8Z  阅读(37)  评论(0编辑  收藏  举报