zoukankan      html  css  js  c++  java
  • 反射效率问题及提高

    package com.zby;
    
    import java.lang.reflect.Method;
    
    public class TestBase64 {
        private static final int INVOKE_TIME=1000000000;
        public static void test01() {
            User user = new User();
            long startTime = System.currentTimeMillis();
            for (int i = 0; i < INVOKE_TIME; i++) {
                user.getName();//直接通过对象调用getName方法
            }
            long endTime = System.currentTimeMillis();
            System.out.println("普通方法调用,执行10亿次,耗时:" + (endTime - startTime) + "ms");
        }
    
        public static void test02() throws Exception {
            User user = new User();
            Class<User> clazz = User.class;
            Method method = clazz.getDeclaredMethod("getName");
            long startTime = System.currentTimeMillis();
            for (int i = 0; i < INVOKE_TIME; i++) {
                method.invoke(user);//通过反射调用getName方法
            }
    
            long endTime = System.currentTimeMillis();
            System.out.println("反射动态方法调用,执行10亿次,耗时:" + (endTime - startTime) + "ms");
        }
    
        public static void test03() throws Exception {
            User user = new User();
            Class<User> clazz = User.class;
            Method method = clazz.getDeclaredMethod("getName");
            method.setAccessible(true); // 不需要执行访问安全检查
            long startTime = System.currentTimeMillis();
            for (int i = 0; i < INVOKE_TIME; i++) {
                method.invoke(user);//通过反射调用getName方法
            }
            long endTime = System.currentTimeMillis();
            System.out.println("反射动态方法调用,跳过安全检查,执行10亿次,耗时:" + (endTime - startTime) + "ms");
        }
    
        public static void main(String[] args) throws Exception {
            test01();
            test02();
            test03();
        }
    }
    
    class User {
        private String name="zby";
        public String getName() {
            return name;
        }
    }
    普通方法调用,执行10亿次,耗时:4ms
    反射动态方法调用,执行10亿次,耗时:157881ms
    反射动态方法调用,跳过安全检查,执行10亿次,耗时:992ms
  • 相关阅读:
    洛谷 U141580 简化罗波切问题
    洛谷 U141578 维修电路
    洛谷 U140760 狭义公因子
    CF75C Modified GCD
    算法题-求解斐波那切数列的第N个数是几?
    算法题-求N的阶乘
    JAVA8新特性
    nginx启动脚本,手动编辑
    javah生成带有包名的头文件
    Matlab图像处理(03)-基本概念
  • 原文地址:https://www.cnblogs.com/zby9527/p/7662343.html
Copyright © 2011-2022 走看看