java注解与反射(7)——分析性能,普通方式调用与反射调用与关闭检测的反射调用:狂神说笔记

通过代码的方式来检验三种方式调用的效率

//分析性能问题
public class Test10 {
    //普通方式调用
    public static void test01(){
        User user1 = new User();

        long startTime =System.currentTimeMillis();
        for (int i = 0; i < 1000000000; i++) {
            user1.getName();
        }
        long endTime = System.currentTimeMillis();

        System.out.println("普通执行10亿次:"+ (endTime-startTime) +"ms");
    }
    //反射方式调用
    public static void test02() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        User user1 = new User();
        Class c1 = user1.getClass();

        Method getName = c1.getMethod("getName");

        long startTime =System.currentTimeMillis();
        for (int i = 0; i < 1000000000; i++) {
            getName.invoke(user1);
        }
        long endTime = System.currentTimeMillis();

        System.out.println("反射方式执行10亿次:"+ (endTime-startTime) +"ms");
    }

    //反射方式调用,关闭检测
    public static void test03() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        User user1 = new User();
        Class c1 = user1.getClass();

        Method getName = c1.getMethod("getName");
        getName.setAccessible(true);

        long startTime =System.currentTimeMillis();
        for (int i = 0; i < 1000000000; i++) {
            getName.invoke(user1);
        }
        long endTime = System.currentTimeMillis();

        System.out.println("关闭检测执行10亿次:"+ (endTime-startTime) +"ms");
    }

    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        test01();
        test02();
        test03();
    }

如图所示,三个方法分别用普通方法、反射和关闭检测的放射来调用10亿次getName的方法,通过时间差来反应其效率。

运行结果:
在这里插入图片描述
由此可见,普通执行的性能>关闭检测反射执行的性能>反射执行的性能

笔记根据b站狂神说视频:https://www.bilibili.com/video/BV1p4411P7V3?p=14

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

木子 旭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值