java反射耗时测试

java反射相对与普通的对象调用原理上来说更加耗时,在调用次数较少的情况下可忽略性能损失,但当调用次数非常多时,需要考虑到此问题,即调用次数过多时不宜使用反射,以下举例:

package com.test.reflection;

import java.lang.reflect.Method;

public class ReflectionDemo {

    public static void main(String[] args) throws Exception {
        // 常规方式
        Student student = new Student();
        long startNormal = System.currentTimeMillis();
        for (int i = 0; i < 1000000; i++) {
            student.setName("hello");
        }
        System.out.println("timeNormal=" + (System.currentTimeMillis() - startNormal));

        //反射方式
        Class<?> cla=Class.forName("com.test.reflection.Student");
        long startReflection = System.currentTimeMillis();
        for (int i = 0; i < 1000000; i++) {
            Method method=cla.getDeclaredMethod("setName", String.class);
            method.invoke(cla.newInstance(), "hello");
        }
        System.out.println("timeReflection=" + (System.currentTimeMillis() - startReflection));
    }

    

}

运行结果:

timeNormal=8
timeReflection=537

这是在简单使用反射调用某个方法的场景下1000000调用的性能差距。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值