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
  • 相关阅读:
    Python爬取优质高清壁纸网站:彼岸
    xpath爬取喜马拉雅糗事播报音频地址
    Pyquery爬取豆瓣电影Top250
    pipenv虚拟环境
    pip报No module named 'pip'错怎么处理?
    SVN的使用
    测试报告
    软件测试分类
    测试模型
    软件开发过程模型
  • 原文地址:https://www.cnblogs.com/zby9527/p/7662343.html
Copyright © 2011-2022 走看看