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
  • 相关阅读:
    网络连接 长连接 短链接
    提升系统的QPS和吞吐量
    QPS/TPS/并发量/系统吞吐量的概念
    spring与mybatis四种整合方法
    理解HTTP之keep-alive
    MyBatis 3 使用注解配置SQL映射器
    Dubbo -- Simple Monitor
    Dubbo后台管理和监控中心部署
    Socket通讯-Netty框架实现Java通讯
    Netty 能做什么
  • 原文地址:https://www.cnblogs.com/zby9527/p/7662343.html
Copyright © 2011-2022 走看看