通过普通方式调用和反射方式调用以及关闭检测后,通过反射方式调用的性能对比

测试代码如下:

package Collections;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class text3 {
    //普通方式调用
    public static void text1() {
        person user = new person();
        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 text2() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        person user = new person();
        Class c = user.getClass();
        Method getName = c.getDeclaredMethod("getName", null);
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 1000000000; i++) {
            getName.invoke("person", null);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("反射方式执行10亿次;" + (endTime - startTime) + "ms");
    }

    //关闭检测后,通过反射的方式调用
    public static void text3() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        person user = new person();
        Class c = user.getClass();
        Method getName = c.getDeclaredMethod("getName", null);
        getName.setAccessible(true);
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 1000000000; i++) {
            getName.invoke("person", null);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("关闭检测后,执行10亿次;" + (endTime - startTime) + "ms");
    }

    public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException {
        text1();
        text2();
        text3();
    }
}

输出:

普通方式执行10亿次;4ms
反射方式执行10亿次;6576ms
关闭检测后,执行10亿次;5577ms
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

从未止步..

谢谢你的打赏,我会继续努力!

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

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

打赏作者

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

抵扣说明:

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

余额充值