BeanUtils工具(Java属性复制工具)

652 阅读1分钟

参考文章:

www.hollischuang.com/archives/53…

常见Java属性复制工具

1.Spring BeanUtils

优点:Spring自带,无需额外引入依赖;效率较高

缺点:运行期生成bean映射,代码级别的错误会延迟到运行时暴露

2.Cglib BeanCopier

优点:性能较高

3.Apache BeanUtils

缺点:性能较低

4.Apache PropertyUtils

缺点:性能较低

5.Dozer

优点:可以很好的和Spring结合,可以通过配置文件等进行属性之间的映射

缺点:性能较低

6.MapStruct

参考文章:juejin.cn/post/685921…

优点:性能快,基于原生,编译期生成bean映射,确保高性能,问题提前暴露

缺点:配置繁琐,每一种数据转化都需要增加一个convert接口

性能比较

工具类

执行1000次耗时

执行10000次耗时

执行100000次耗时

执行1000000次耗时   

Spring BeanUtils

5ms

10ms

45ms

169ms

Cglib BeanCopier

4ms

18ms

45ms

91ms

Apache PropertyUtils

60ms

265ms

1444ms

11492ms

Apache BeanUtils

138ms

816ms

4154ms

36938ms

Dozer

566ms

2254ms

11136ms

102965ms

MapStruct

             0ms

                1ms

                      3ms

                       6ms

综上,我们基本可以得出结论,在性能方面,Spring BeanUtils和Cglib BeanCopier表现比较不错,而Apache PropertyUtils、Apache BeanUtils以及Dozer则表现的很不好。

总结:

若对性能无特别要求,推荐使用Spring BeanUtils/Cglib BeanCopier

若对性能有要求且希望错误在编译期暴露,推荐使用MapStruct

其他不推荐使用Apache PropertyUtils和 Apache BeanUtils 性能较差,Dozer已经很长时间没更新维护了