java反射性能

一直听说java反射性能不太好,今天就好奇简单测试一下。下面是测试代码:

package com.koma.mode.test;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Create by koma on 2017/12/20
 */
public class Test {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        long num = 0;
        // new一个Student对象
        Student student = new Student();
        long before = System.currentTimeMillis();
        for (long i = 0; i < 10000000; i++) {
            student.setAge(i);
            num += student.getAge();
        }
        long after = System.currentTimeMillis() - before;
        System.out.println("new时间:" + after+" 总数:"+num);

        // 得到Student的class对象
        Class<?> aClass = Class.forName("com.koma.mode.test.Student");
        Object o = aClass.newInstance();
        Method setAge = aClass.getMethod("setAge", Long.class);
        Method getAge = aClass.getMethod("getAge");
        long count = 0;
        before=System.currentTimeMillis();
        for (long i = 0; i < 10000000; i++) {
            setAge.invoke(o, i);
            Long tmp = (Long) getAge.invoke(o);
            count += tmp;
        }
        after=System.currentTimeMillis()-before;
        System.out.println("class时间:"+after+" 总数:"+count);

    }
}

结果如下:

new时间:96 总数:49999995000000
class时间:185 总数:49999995000000

总结:我用的jdk版本是1.8.0_91,发现用反射性能也还好,不是太低,随着jdk版本越来越高,反射的性能也优化的越来越好。印象当中性能不好,可能还停留在jdk6以前。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值