博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用esotericsoftware高速缓存(ASM)的BeanUtils.copyProperties!高性能!
阅读量:4154 次
发布时间:2019-05-25

本文共 9673 字,大约阅读时间需要 32 分钟。

一、事出有因

项目中使用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.*;/** * 
* 使用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
methodMap = new HashMap
(); private static Map
methodIndexMap = new HashMap
(); private static Map
> fieldMap = new HashMap
>(); /** * Description
* 重写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
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
* 单例模式 * @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
fieldList = new ArrayList
(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几毫秒,效率已经没问题了; 

转载地址:http://uzgti.baihongyu.com/

你可能感兴趣的文章
将有序数组转换为平衡二叉搜索树
查看>>
最长递增子序列
查看>>
从一列数中筛除尽可能少的数,使得从左往右看这些数是从小到大再从大到小...
查看>>
判断一个整数是否是回文数
查看>>
腾讯的一道面试题—不用除法求数字乘积
查看>>
素数算法
查看>>
java多线程环境单例模式实现详解
查看>>
将一个数插入到有序的数列中,插入后的数列仍然有序
查看>>
在有序的数列中查找某数,若该数在此数列中,则输出它所在的位置,否则输出no found
查看>>
万年历
查看>>
作为码农你希望面试官当场指出你错误么?有面试官这样遭到投诉!
查看>>
好多程序员都认为写ppt是很虚的技能,可事实真的是这样么?
查看>>
如果按照代码行数发薪水会怎样?码农:我能刷到公司破产!
查看>>
程序员失误造成服务停用3小时,只得到半月辞退补偿,发帖喊冤
查看>>
阿里p8程序员四年提交6000次代码的确有功,但一次错误让人唏嘘!
查看>>
一道技术问题引起的遐想,最后得出结论技术的本质是多么的朴实!
查看>>
985硕士:非科班自学编程感觉还不如培训班出来的,硕士白读了?
查看>>
你准备写代码到多少岁?程序员们是这么回答的!
查看>>
码农:和产品对一天需求,产品经理的需求是对完了,可我代码呢?
查看>>
程序员过年回家该怎么给亲戚朋友解释自己的职业?
查看>>