使用esotericsoftware高速緩存(ASM)的BeanUtils.copyProperties!高性能!

一、事出有因

項目中使用BeanUtils.copyProperties但是其性能又不是很滿意,

而且阿里發佈了阿里巴巴代碼規約插件指明瞭在Apache BeanUtils.copyProperties()方法後面打了個大大的紅叉,提示"避免使用Apache的BeanUtils進行屬性的copy"。心裏確實不是滋味,從小老師就教導我們,"凡是Apache寫的框架都是好框架",怎麼可能會存在"性能問題"--還是這種猿們所不能容忍的問題。心存着對BeanUtils的懷疑開始了今天的研究之路。

二、市面上的其他幾種屬性copy工具

  1. springframework的BeanUtils
  2. cglib的BeanCopier
  3. Apache BeanUtils包的PropertyUtils類

三、下面來測試一下性能。

private static void testCglibBeanCopier(OriginObject origin, int len) {
        Stopwatch stopwatch = Stopwatch.createStarted();
        System.out.println();
        System.out.println("================cglib BeanCopier執行" + len + "次================");
        DestinationObject destination3 = new DestinationObject();

        for (int i = 0; i < len; i++) {
            BeanCopier copier = BeanCopier.create(OriginObject.class, DestinationObject.class, false);
            copier.copy(origin, destination3, null);
        }
        stopwatch.stop();

        System.out.println("testCglibBeanCopier 耗時: " + stopwatch.elapsed(TimeUnit.MILLISECONDS));
    }

    private static void testApacheBeanUtils(OriginObject origin, int len)
            throws IllegalAccessException, InvocationTargetException {
        Stopwatch stopwatch = Stopwatch.createStarted();
        System.out.println();
        System.out.println("================apache BeanUtils執行" + len + "次================");
        DestinationObject destination2 = new DestinationObject();
        for (int i = 0; i < len; i++) {
            BeanUtils.copyProperties(destination2, origin);
        }

        stopwatch.stop();

        System.out.println("testApacheBeanUtils 耗時: " + stopwatch.elapsed(TimeUnit.MILLISECONDS));
    }

    private static void testSpringFramework(OriginObject origin, int len) {
        Stopwatch stopwatch = Stopwatch.createStarted();
        System.out.println("================springframework執行" + len + "次================");
        DestinationObject destination = new DestinationObject();

        for (int i = 0; i < len; i++) {
            org.springframework.beans.BeanUtils.copyProperties(origin, destination);
        }

        stopwatch.stop();

        System.out.println("testSpringFramework 耗時: " + stopwatch.elapsed(TimeUnit.MILLISECONDS));
    }

    private static void testApacheBeanUtilsPropertyUtils(OriginObject origin, int len)
            throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
        Stopwatch stopwatch = Stopwatch.createStarted();
        System.out.println();
        System.out.println("================apache BeanUtils PropertyUtils執行" + len + "次================");
        DestinationObject destination2 = new DestinationObject();
        for (int i = 0; i < len; i++) {
            PropertyUtils.copyProperties(destination2, origin);
        }

        stopwatch.stop();

        System.out.println("testApacheBeanUtilsPropertyUtils 耗時: " + stopwatch.elapsed(TimeUnit.MILLISECONDS));
    }

分別執行1000、10000、100000、1000000次耗時數(毫秒):

工具名稱 執行1000次耗時 10000次 100000次 1000000次
Apache BeanUtils 390ms 854ms 1763ms 8408ms
Apache PropertyUtils 26ms 221ms 352ms 2663ms
spring BeanUtils 39ms 315ms 373ms 949ms
Cglib BeanCopier 64ms 144ms 171ms 309ms

結論:

  1. Apache BeanUtils的性能最差,不建議使用。
  2. Apache PropertyUtils100000次以內性能還能接受,到百萬級別性能就比較差了,可酌情考慮。
  3. spring BeanUtils和BeanCopier性能較好,如果對性能有特別要求,可使用BeanCopier,不然spring BeanUtils也是可取的。

4、再來看看反射的性能對比

我們先通過簡單的代碼來看看,各種調用方式之間的性能差距。

public static void main(String[] args) throws Exception {
        ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"spring-common.xml"});    
        new InitMothods().initApplicationContext(ac);
        
        
        long now;
        HttpRouteClassAndMethod route = InitMothods.getTaskHandler("GET:/login/getSession");
        Map map = new HashMap();
        
        //-----------------------最粗暴的直接調用
        
        now = System.currentTimeMillis();
         
        for(int i = 0; i<5000000; ++i){
            new LoginController().getSession(map);
        }
        System.out.println("get耗時"+(System.currentTimeMillis() - now) + "ms);
        
        
        //---------------------常規的invoke
        
        now = System.currentTimeMillis();
         
        for(int i = 0; i<5000000; ++i){
            Class<?> c = Class.forName("com.business.controller.LoginController");
           
            Method m = c.getMethod("getSession",Map.class);
            m.invoke(SpringApplicationContextHolder.getSpringBeanForClass(route.getClazz()), map);
        }
        System.out.println("標準反射耗時"+(System.currentTimeMillis() - now) + "ms);
        
         
        //---------------------緩存class的invoke
        
        now = System.currentTimeMillis();
         
        for(int i = 0; i<5000000; ++i){
            try {
                route.getMethod().invoke(SpringApplicationContextHolder.getSpringBeanForClass(route.getClazz()),
                        new Object[]{map});
            } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                // TODO 自動生成的 catch 塊
                e.printStackTrace();
            }
        }
         
        System.out.println("緩存反射耗時"+(System.currentTimeMillis() - now) + "ms秒);
        
        
        //---------------------reflectasm的invoke
        
        MethodAccess ma = MethodAccess.get(route.getClazz());
        int index = ma.getIndex("getSession");
        now = System.currentTimeMillis();
         
        for(int i = 0; i<5000000; ++i){
            ma.invoke(SpringApplicationContextHolder.getSpringBeanForClass(route.getClazz()), index, map);
        }
        System.out.println("reflectasm反射耗時"+(System.currentTimeMillis() - now) + "ms);
 
    }

每種方式執行500W次運行結果如下:

  • get耗時21ms
  • 標準反射耗時5397ms
  • 緩存反射耗時315ms
  • reflectasm反射耗時275ms

(時間長度請忽略,因爲每個人的代碼業務不一致,主要看體現的差距,多次運行效果基本一致。)

結論:方法直接調用屬於最快的方法,其次是java最基本的反射,而反射中又分是否緩存class兩種,由結果得出其實反射中很大一部分時間是在查找class,實際invoke效率還是不錯的。而reflectasm反射效率要在java傳統的反射之上快了接近1/3.

感謝前人的博客@生活創客

有的時候爲了複用性,通用型,我們不得不犧牲掉一些性能。

google是學習的進步階梯,咱們沒事兒就看看前人的經驗,總結一下,搞出來一個滿意的!

 

ReflectASM,高性能的反射:

什麼是ReflectASM    ReflectASM是一個很小的java類庫,主要是通過asm生產類來實現java反射,執行速度非常快,看了網上很多和反射的對比,覺得ReflectASM比較神奇,很想知道其原理,下面介紹下如何使用及原理;

public static void main(String[] args) {  
        User user = new User();  
        //使用reflectasm生產User訪問類  
        MethodAccess access = MethodAccess.get(User.class);  
        //invoke setName方法name值  
        access.invoke(user, "setName", "張三");  
        //invoke getName方法 獲得值  
        String name = (String)access.invoke(user, "getName", null);  
        System.out.println(name);  
    }  


原理 
   上面代碼的確實現反射的功能,代碼主要的核心是 MethodAccess.get(User.class); 
看了下源碼,這段代碼主要是通過asm生產一個User的處理類 UserMethodAccess(這個類主要是實現了invoke方法)的ByteCode,然後獲得該對象,通過上面的invoke操作user類。 
ASM反射轉換:

package com.jd.jdjr.ras.utils;

import com.esotericsoftware.reflectasm.MethodAccess;
import org.apache.commons.lang.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.*;

/**
 * <Description>
 * 使用google的高速緩存ASM實現的beancopy
 * 兼容編譯器自動生成的關於boolean類型的參數 get方法是is的!
 * @author Mr.Sunny
 * @version 1.0
 * @createDate 2020/5/14 5:16 下午
 * @see BeanUtils.java 
 */
public class BeanUtils {
    //靜態的,類型爲HashMap的成員變量,用於存儲緩存數據
    private static Map<Class, MethodAccess> methodMap = new HashMap<Class, MethodAccess>();

    private static Map<String, Integer> methodIndexMap = new HashMap<String, Integer>();

    private static Map<Class, List<String>> fieldMap = new HashMap<Class, List<String>>();

    /**
     * Description <br>
     * 重寫bean的copy方法
     * @Author: Mr..Sunny
     * @Date: 2020/5/14 5:12 下午
     * @param target 目標  to
     * @param source 來源  from
     * @return: void
     */
    public static void copyProperties(Object target, Object source) {
        MethodAccess descMethodAccess = methodMap.get(target.getClass());
        if (descMethodAccess == null) {
            descMethodAccess = cache(target);
        }
        MethodAccess orgiMethodAccess = methodMap.get(source.getClass());
        if (orgiMethodAccess == null) {
            orgiMethodAccess = cache(source);
        }

        List<String> fieldList = fieldMap.get(source.getClass());
        for (String field : fieldList) {
            String getKey = source.getClass().getName() + "." + "get" + field;
            String setkey = target.getClass().getName() + "." + "set" + field;
            Integer setIndex = methodIndexMap.get(setkey);
            if (setIndex != null) {
                int getIndex = methodIndexMap.get(getKey);
                // 參數一需要反射的對象
                // 參數二class.getDeclaredMethods 對應方法的index
                // 參數對三象集合
                descMethodAccess.invoke(target, setIndex.intValue(),
                        orgiMethodAccess.invoke(source, getIndex));
            }
        }
    }

    /**
     * Description <br> 
     * 單例模式
     * @Author: Mr.Sunny
     * @Date: 2020/5/14 5:17 下午
     * @param orgi    from
     * @return: com.esotericsoftware.reflectasm.MethodAccess 
     */
    private static MethodAccess cache(Object orgi) {
        synchronized (orgi.getClass()) {
            MethodAccess methodAccess = MethodAccess.get(orgi.getClass());
            Field[] fields = orgi.getClass().getDeclaredFields();
            List<String> fieldList = new ArrayList<String>(fields.length);
            for (Field field : fields) {
                if (Modifier.isPrivate(field.getModifiers())
                        && !Modifier.isStatic(field.getModifiers())) { // 是否是私有的,是否是靜態的
                    // 非公共私有變量
                    String fieldName = StringUtils.capitalize(field.getName()); // 獲取屬性名稱
                    int getIndex = 0; // 獲取get方法的下標
                    try {
                        getIndex = methodAccess.getIndex("get" + fieldName);
                    } catch (Exception e) {
                        getIndex = methodAccess.getIndex("is"+(fieldName.replaceFirst("Is","")));
                    }
                    int setIndex = 0; // 獲取set方法的下標
                    try {
                        setIndex = methodAccess.getIndex("set" + fieldName);
                    } catch (Exception e) {
                        setIndex = methodAccess.getIndex("set" + fieldName.replaceFirst("Is",""));
                    }
                    methodIndexMap.put(orgi.getClass().getName() + "." + "get"
                            + fieldName, getIndex); // 將類名get方法名,方法下標註冊到map中
                    methodIndexMap.put(orgi.getClass().getName() + "." + "set"
                            + fieldName, setIndex); // 將類名set方法名,方法下標註冊到map中
                    fieldList.add(fieldName); // 將屬性名稱放入集合裏
                }
            }
            fieldMap.put(orgi.getClass(), fieldList); // 將類名,屬性名稱註冊到map中
            methodMap.put(orgi.getClass(), methodAccess);
            return methodAccess;
        }
    }
}

最終測試性能:

執行1000000條效率80幾毫秒,效率已經沒問題了; 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章