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
  • 相关阅读:
    软件工程 四则运算 基于控制台。
    新学期 新气象
    http://www.cnblogs.com/091JN/
    201421123091 ONLY-JN
    201421123091 ONLY-JN
    C语言课程学习的总结
    实验13——结构体、文件的基本应用
    实验12——指针的基础应用2
    实验11——指针的基础应用
    实验十——一维数组的定义及引用
  • 原文地址:https://www.cnblogs.com/zby9527/p/7662343.html
Copyright © 2011-2022 走看看