Apache BeanUtils与Spring BeanUtils的拷贝性能比较

本文对比了Apache BeanUtils和Spring BeanUtils在对象拷贝时的性能,通过测试发现Apache BeanUtils的拷贝耗时显著长于Spring BeanUtils,尤其在大量字段的JavaBean中,差距更大。同时,文章提到了其他对象拷贝工具如MapStruct、Dozer和ModelMapper等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Apache BeanUtils需要引入的包:

        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.4</version>
        </dependency>

测试同一个对象使用两种拷贝方法的耗时,具体代码如下,

 @Test
    void Copy() throws InvocationTargetException, IllegalAccessException {

        UserInfo userData = this.userInfoService.getUserData("0951d015472946fcbc039f9dff6f13c3");
        UserInfo springBean = new UserInfo();
        long springBegin = System.currentTimeMillis();
        BeanUtils.copyProperties(userData,springBean);
        long springAfter = System.currentTimeMillis();
        System.out.println("共耗时" + (springAfter - springBegin) + "毫秒");


        UserInfo apacheBean = new UserInfo();
        long apacheBegin = System.currentTimeMillis();
        org.apache.commons.beanutils.BeanUtils.copyProperties(apacheBean,userData);
        long apacheAfter = System.currentTimeMillis();
        System.out.println("共耗时" + (apacheAfter - apacheBegin) + "毫秒");

    }

拷贝的对象UserInfo,六个字段,

测试两次的耗时为以下截图:

两次比较,Apache BeanUtils使用的时间明显比Spring BeanUtils要长很多,再加上实际开发环境中,JavaBean拷贝的字段跟多,所以耗时会更长。

 

源码分析:

Apache BeanUtils

public void copyProperties(Object dest, Object orig) throws IllegalAccessException, InvocationTargetException {
        if (dest == null) {
            throw new IllegalArgumentException("No destination bean specified");
        } else if (orig == null) {
            throw new IllegalArgumentException("No origin bean specified");
        } else {
            if (this.log.isDebugEnabled()) {
                this.log.debug("BeanUtils.copyProperties(" + dest + ", " + orig + ")");
            }

            int var5;
            int var6;
            String name;
            Object value;
            if (orig instanceof DynaBean) {
                DynaProperty[] origDescriptors = ((DynaBean)orig).getDynaClass().getDynaProperties();
                DynaProperty[] var4 = origDescriptors;
                var5 = origDescriptors.length;

                for(var6 = 0; var6 < var5; ++var6) {
                    DynaProperty origDescriptor = var4[var6];
                    name = origDescriptor.getName();
                    if (this.getPropertyUtils().isReadable(orig, name) && this.getPropertyUtils().isWriteable(dest, name)) {
                        value = ((DynaBean)orig).get(name);
                        this.copyProperty(dest, name, value);
                    }
                }
            } else if (orig instanceof Map) {
                Map<String, Object> propMap = (Map)orig;
                Iterator var13 = propMap.entrySet().iterator();

                while(var13.hasNext()) {
                    Entry<String, Object> entry = (Entry)var13.next();
                    String name = (String)entry.getKey();
                    if (this.getPropertyUtils().isWriteable(dest, name)) {
                        this.copyProperty(dest, name, entry.getValue());
                    }
                }
            } else {
                PropertyDescriptor[] origDescriptors = this.getPropertyUtils().getPropertyDescriptors(orig);
                PropertyDescriptor[] var14 = origDescriptors;
                var5 = origDescriptors.length;

                for(var6 = 0; var6 < var5; ++var6) {
                    PropertyDescriptor origDescriptor = var14[var6];
                    name = origDescriptor.getName();
                    if (!"class".equals(name) && this.getPropertyUtils().isReadable(orig, name) && this.getPropertyUtils().isWriteable(dest, name)) {
                        try {
                            value = this.getPropertyUtils().getSimpleProperty(orig, name);
                            this.copyProperty(dest, name, value);
                        } catch (NoSuchMethodException var10) {
                        }
                    }
                }
            }

        }
    }

Apache BeanUtils一上来先进行了三个if判断,之后在进行对象拷贝,而Spring BeanUtils则简单多了。

private static void copyProperties(Object source, Object target, @Nullable Class<?> editable,
			@Nullable String... ignoreProperties) throws BeansException {

		Assert.notNull(source, "Source must not be null");
		Assert.notNull(target, "Target must not be null");

		Class<?> actualEditable = target.getClass();
		if (editable != null) {
			if (!editable.isInstance(target)) {
				throw new IllegalArgumentException("Target class [" + target.getClass().getName() +
						"] not assignable to Editable class [" + editable.getName() + "]");
			}
			actualEditable = editable;
		}
		PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
		List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);

		for (PropertyDescriptor targetPd : targetPds) {
			Method writeMethod = targetPd.getWriteMethod();
			if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
				PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
				if (sourcePd != null) {
					Method readMethod = sourcePd.getReadMethod();
					if (readMethod != null &&
							ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
						try {
							if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
								readMethod.setAccessible(true);
							}
							Object value = readMethod.invoke(source);
							if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
								writeMethod.setAccessible(true);
							}
							writeMethod.invoke(target, value);
						}
						catch (Throwable ex) {
							throw new FatalBeanException(
									"Could not copy property '" + targetPd.getName() + "' from source to target", ex);
						}
					}
				}
			}
		}
	}

除了以上两种拷贝对象的工具类,还有MapStruct、Dozer和ModelMapper等等。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值