使用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

相关文章

Java中流式并行操作parallelStream的原理和使用方法

《Java中流式并行操作parallelStream的原理和使用方法》本文详细介绍了Java中的并行流(parallelStream)的原理、正确使用方法以及在实际业务中的应用案例,并指出在使用并行流... 目录Java中流式并行操作parallelStream0. 问题的产生1. 什么是parallelS

Linux join命令的使用及说明

《Linuxjoin命令的使用及说明》`join`命令用于在Linux中按字段将两个文件进行连接,类似于SQL的JOIN,它需要两个文件按用于匹配的字段排序,并且第一个文件的换行符必须是LF,`jo... 目录一. 基本语法二. 数据准备三. 指定文件的连接key四.-a输出指定文件的所有行五.-o指定输出

Linux jq命令的使用解读

《Linuxjq命令的使用解读》jq是一个强大的命令行工具,用于处理JSON数据,它可以用来查看、过滤、修改、格式化JSON数据,通过使用各种选项和过滤器,可以实现复杂的JSON处理任务... 目录一. 简介二. 选项2.1.2.2-c2.3-r2.4-R三. 字段提取3.1 普通字段3.2 数组字段四.

Linux kill正在执行的后台任务 kill进程组使用详解

《Linuxkill正在执行的后台任务kill进程组使用详解》文章介绍了两个脚本的功能和区别,以及执行这些脚本时遇到的进程管理问题,通过查看进程树、使用`kill`命令和`lsof`命令,分析了子... 目录零. 用到的命令一. 待执行的脚本二. 执行含子进程的脚本,并kill2.1 进程查看2.2 遇到的

详解SpringBoot+Ehcache使用示例

《详解SpringBoot+Ehcache使用示例》本文介绍了SpringBoot中配置Ehcache、自定义get/set方式,并实际使用缓存的过程,文中通过示例代码介绍的非常详细,对大家的学习或者... 目录摘要概念内存与磁盘持久化存储:配置灵活性:编码示例引入依赖:配置ehcache.XML文件:配置

Java 虚拟线程的创建与使用深度解析

《Java虚拟线程的创建与使用深度解析》虚拟线程是Java19中以预览特性形式引入,Java21起正式发布的轻量级线程,本文给大家介绍Java虚拟线程的创建与使用,感兴趣的朋友一起看看吧... 目录一、虚拟线程简介1.1 什么是虚拟线程?1.2 为什么需要虚拟线程?二、虚拟线程与平台线程对比代码对比示例:三

k8s按需创建PV和使用PVC详解

《k8s按需创建PV和使用PVC详解》Kubernetes中,PV和PVC用于管理持久存储,StorageClass实现动态PV分配,PVC声明存储需求并绑定PV,通过kubectl验证状态,注意回收... 目录1.按需创建 PV(使用 StorageClass)创建 StorageClass2.创建 PV

Redis 基本数据类型和使用详解

《Redis基本数据类型和使用详解》String是Redis最基本的数据类型,一个键对应一个值,它的功能十分强大,可以存储字符串、整数、浮点数等多种数据格式,本文给大家介绍Redis基本数据类型和... 目录一、Redis 入门介绍二、Redis 的五大基本数据类型2.1 String 类型2.2 Hash

Redis中Hash从使用过程到原理说明

《Redis中Hash从使用过程到原理说明》RedisHash结构用于存储字段-值对,适合对象数据,支持HSET、HGET等命令,采用ziplist或hashtable编码,通过渐进式rehash优化... 目录一、开篇:Hash就像超市的货架二、Hash的基本使用1. 常用命令示例2. Java操作示例三

Linux创建服务使用systemctl管理详解

《Linux创建服务使用systemctl管理详解》文章指导在Linux中创建systemd服务,设置文件权限为所有者读写、其他只读,重新加载配置,启动服务并检查状态,确保服务正常运行,关键步骤包括权... 目录创建服务 /usr/lib/systemd/system/设置服务文件权限:所有者读写js,其他