简单测试普通方法 反射方法 关闭安全监测反射 调用 类的方法速度

package Reflection;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/*
普通方法执行10亿次时间2ms
反射方法执行10亿次时间2660ms
关闭安全检测执行10亿次时间1634ms
 */
//分析性能问题
public class Demo04 {

    public static void test01(){
        long startTime = System.currentTimeMillis();
        for (int i = 0; i <10_0000_0000 ; i++) {
            User.test();
        }
        long endTime = System.currentTimeMillis();
        System.out.println("普通方法执行10亿次时间"+(endTime-startTime)+"ms");
    }

    public static void test02() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        long startTime = System.currentTimeMillis();
        User user = new User();
        Class c = user.getClass();
        Method method = c.getMethod("test",null);

        for (int i = 0; i <10_0000_0000 ; i++) {
            method.invoke(user, null);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("反射方法执行10亿次时间"+(endTime-startTime)+"ms");
    }

    public static void test03() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        long startTime = System.currentTimeMillis();
        User user = new User();
        Class c = user.getClass();
        Method method = c.getMethod("test",null);
        method.setAccessible(true);
        for (int i = 0; i <10_0000_0000 ; i++) {
            method.invoke(user, null);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("关闭安全检测执行10亿次时间"+(endTime-startTime)+"ms");
    }


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




class User{
    private String name;
    int age;

    public User() {
    }

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public static void say(String str){
        System.out.println(str);
    }

    public static void test(){

    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age='" + age + '\'' +
                '}';
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值