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

相关文章

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

Windows下C++使用SQLitede的操作过程

《Windows下C++使用SQLitede的操作过程》本文介绍了Windows下C++使用SQLite的安装配置、CppSQLite库封装优势、核心功能(如数据库连接、事务管理)、跨平台支持及性能优... 目录Windows下C++使用SQLite1、安装2、代码示例CppSQLite:C++轻松操作SQ

Python常用命令提示符使用方法详解

《Python常用命令提示符使用方法详解》在学习python的过程中,我们需要用到命令提示符(CMD)进行环境的配置,:本文主要介绍Python常用命令提示符使用方法的相关资料,文中通过代码介绍的... 目录一、python环境基础命令【Windows】1、检查Python是否安装2、 查看Python的安

Python并行处理实战之如何使用ProcessPoolExecutor加速计算

《Python并行处理实战之如何使用ProcessPoolExecutor加速计算》Python提供了多种并行处理的方式,其中concurrent.futures模块的ProcessPoolExecu... 目录简介完整代码示例代码解释1. 导入必要的模块2. 定义处理函数3. 主函数4. 生成数字列表5.

Python中help()和dir()函数的使用

《Python中help()和dir()函数的使用》我们经常需要查看某个对象(如模块、类、函数等)的属性和方法,Python提供了两个内置函数help()和dir(),它们可以帮助我们快速了解代... 目录1. 引言2. help() 函数2.1 作用2.2 使用方法2.3 示例(1) 查看内置函数的帮助(

Linux脚本(shell)的使用方式

《Linux脚本(shell)的使用方式》:本文主要介绍Linux脚本(shell)的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录概述语法详解数学运算表达式Shell变量变量分类环境变量Shell内部变量自定义变量:定义、赋值自定义变量:引用、修改、删

Java使用HttpClient实现图片下载与本地保存功能

《Java使用HttpClient实现图片下载与本地保存功能》在当今数字化时代,网络资源的获取与处理已成为软件开发中的常见需求,其中,图片作为网络上最常见的资源之一,其下载与保存功能在许多应用场景中都... 目录引言一、Apache HttpClient简介二、技术栈与环境准备三、实现图片下载与保存功能1.

Python中使用uv创建环境及原理举例详解

《Python中使用uv创建环境及原理举例详解》uv是Astral团队开发的高性能Python工具,整合包管理、虚拟环境、Python版本控制等功能,:本文主要介绍Python中使用uv创建环境及... 目录一、uv工具简介核心特点:二、安装uv1. 通过pip安装2. 通过脚本安装验证安装:配置镜像源(可

LiteFlow轻量级工作流引擎使用示例详解

《LiteFlow轻量级工作流引擎使用示例详解》:本文主要介绍LiteFlow是一个灵活、简洁且轻量的工作流引擎,适合用于中小型项目和微服务架构中的流程编排,本文给大家介绍LiteFlow轻量级工... 目录1. LiteFlow 主要特点2. 工作流定义方式3. LiteFlow 流程示例4. LiteF

使用Python开发一个现代化屏幕取色器

《使用Python开发一个现代化屏幕取色器》在UI设计、网页开发等场景中,颜色拾取是高频需求,:本文主要介绍如何使用Python开发一个现代化屏幕取色器,有需要的小伙伴可以参考一下... 目录一、项目概述二、核心功能解析2.1 实时颜色追踪2.2 智能颜色显示三、效果展示四、实现步骤详解4.1 环境配置4.