Java 一般方式调用方法和使用反射调用方法的性能对比,以及反射调优

1、首先我们对二者的执行速度做一个比较:
调用9000万次累加,观察二者花费的时间
2、然后我们给出调优的方法——关闭访问检查setAccessible(true)
观察调优后花费的时间

代码:

package reflect_optimize;

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

/**
 * 对比使用传统方式调用方法和使用反射调用方法的速度性能差异
 */
public class SpeedCompare {
    public static void main(String[] args) throws ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchMethodException {
        m1();
        m2();
        m3();
    }

    //1、使用传统方法
    public static void m1(){
        Dog dog = new Dog();
        long start = System.currentTimeMillis();
        for (int i = 0; i < 90000000; i++) { //调用9000万次
            dog.say();
        }
        long end = System.currentTimeMillis();
        System.out.println("1、传统方法用时:" + (end - start));

    }
    //2、使用反射
    public static void m2() throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Class<?> cls = Class.forName("reflect_optimize.Dog");
        Object o = cls.newInstance();
        Method method = cls.getMethod("say");
        long start = System.currentTimeMillis();
        for (int i = 0; i < 90000000; i++) {
            method.invoke(o);
        }
        long end = System.currentTimeMillis();
        System.out.println("2、反射用时:" + (end - start));
    }

    //3、对反射进行优化 ——> 关闭访问检查
    public static void m3() throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Class<?> cls = Class.forName("reflect_optimize.Dog");
        Object o = cls.newInstance();
        Method method = cls.getMethod("say");

        method.setAccessible(true); //这一句就是优化,关闭了访问检查,同样Method、构造器也都有这个方法

        long start = System.currentTimeMillis();
        for (int i = 0; i < 90000000; i++) {
            method.invoke(o);
        }
        long end = System.currentTimeMillis();
        System.out.println("3、优化后的反射用时:" + (end - start));
    }
}

class Dog {
    private int count = 0;
    public void say() {
        count++;
    }
}

执行结果:(单位ms)

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值