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

本文主要是介绍使用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 BeanUtils390ms854ms1763ms8408ms
Apache PropertyUtils26ms221ms352ms2663ms
spring BeanUtils39ms315ms373ms949ms
Cglib BeanCopier64ms144ms171ms309ms

结论:

  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);//---------------------常规的invokenow = 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的invokenow = 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的invokeMethodAccess 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几毫秒,效率已经没问题了; 

这篇关于使用esotericsoftware高速缓存(ASM)的BeanUtils.copyProperties!高性能!的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/721014

相关文章

从零教你安装pytorch并在pycharm中使用

《从零教你安装pytorch并在pycharm中使用》本文详细介绍了如何使用Anaconda包管理工具创建虚拟环境,并安装CUDA加速平台和PyTorch库,同时在PyCharm中配置和使用PyTor... 目录背景介绍安装Anaconda安装CUDA安装pytorch报错解决——fbgemm.dll连接p

Vue项目的甘特图组件之dhtmlx-gantt使用教程和实现效果展示(推荐)

《Vue项目的甘特图组件之dhtmlx-gantt使用教程和实现效果展示(推荐)》文章介绍了如何使用dhtmlx-gantt组件来实现公司的甘特图需求,并提供了一个简单的Vue组件示例,文章还分享了一... 目录一、首先 npm 安装插件二、创建一个vue组件三、业务页面内 引用自定义组件:四、dhtmlx

使用Python创建一个能够筛选文件的PDF合并工具

《使用Python创建一个能够筛选文件的PDF合并工具》这篇文章主要为大家详细介绍了如何使用Python创建一个能够筛选文件的PDF合并工具,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下... 目录背景主要功能全部代码代码解析1. 初始化 wx.Frame 窗口2. 创建工具栏3. 创建布局和界面控件4

一文详解如何在Python中使用Requests库

《一文详解如何在Python中使用Requests库》:本文主要介绍如何在Python中使用Requests库的相关资料,Requests库是Python中常用的第三方库,用于简化HTTP请求的发... 目录前言1. 安装Requests库2. 发起GET请求3. 发送带有查询参数的GET请求4. 发起PO

Java中的Cursor使用详解

《Java中的Cursor使用详解》本文介绍了Java中的Cursor接口及其在大数据集处理中的优势,包括逐行读取、分页处理、流控制、动态改变查询、并发控制和减少网络流量等,感兴趣的朋友一起看看吧... 最近看代码,有一段代码涉及到Cursor,感觉写法挺有意思的。注意是Cursor,而不是Consumer

Node.js net模块的使用示例

《Node.jsnet模块的使用示例》本文主要介绍了Node.jsnet模块的使用示例,net模块支持TCP通信,处理TCP连接和数据传输,具有一定的参考价值,感兴趣的可以了解一下... 目录简介引入 net 模块核心概念TCP (传输控制协议)Socket服务器TCP 服务器创建基本服务器服务器配置选项服

如何使用CSS3实现波浪式图片墙

《如何使用CSS3实现波浪式图片墙》:本文主要介绍了如何使用CSS3的transform属性和动画技巧实现波浪式图片墙,通过设置图片的垂直偏移量,并使用动画使其周期性地改变位置,可以创建出动态且具有波浪效果的图片墙,同时,还强调了响应式设计的重要性,以确保图片墙在不同设备上都能良好显示,详细内容请阅读本文,希望能对你有所帮助...

Rust中的注释使用解读

《Rust中的注释使用解读》本文介绍了Rust中的行注释、块注释和文档注释的使用方法,通过示例展示了如何在实际代码中应用这些注释,以提高代码的可读性和可维护性... 目录Rust 中的注释使用指南1. 行注释示例:行注释2. 块注释示例:块注释3. 文档注释示例:文档注释4. 综合示例总结Rust 中的注释

Linux使用cut进行文本提取的操作方法

《Linux使用cut进行文本提取的操作方法》Linux中的cut命令是一个命令行实用程序,用于从文件或标准输入中提取文本行的部分,本文给大家介绍了Linux使用cut进行文本提取的操作方法,文中有详... 目录简介基础语法常用选项范围选择示例用法-f:字段选择-d:分隔符-c:字符选择-b:字节选择--c

使用Go语言开发一个命令行文件管理工具

《使用Go语言开发一个命令行文件管理工具》这篇文章主要为大家详细介绍了如何使用Go语言开发一款命令行文件管理工具,支持批量重命名,删除,创建,移动文件,需要的小伙伴可以了解下... 目录一、工具功能一览二、核心代码解析1. 主程序结构2. 批量重命名3. 批量删除4. 创建文件/目录5. 批量移动三、如何安