Java实体映射工具MapStruct 与BeanUtils性能比较
本文通过一个简单的示例代码,比较MapStruct和BeanUtils的性能数据,实测一下性能到底有多大的差距。关于MapStruct工具的详细介绍可以参考《Java实体映射工具MapStruct详解》技术专栏,提供完整示例项目代码下载。

MapStruct属于在编译期,生成调用get/set方法进行赋值的代码,生成对应的Java文件。在编译期间消耗少许的时间,换取运行时的高性能。

一、创建测试应用
如图所示,创建测试应用performance-test,用于测试StudentDto对象和Student对象之间的转换。

其中基于MapStruct工具开发的StudentMapper映射接口的代码如下所示:
@Mapper(componentModel = "spring")
public interface StudentMapper {
StudentMapper INSTANCE = Mappers.getMapper(StudentMapper.class);
@Mapping(target = "className", source= "className")
Student getModelFromDto(StudentDto studentDto);
@Mapping(target = "className", source = "className")
//@InheritInverseConfiguration(name = "getModelFromDto")
StudentDto getDtoFromModel(Student student);
}
二、测试代码
分别通过MapStruct 和 BeanUtils 将相同对象转换100W次,看看整体的耗时数据。测试类PerformanceTest的代码如下所示:
public class PerformanceTest {
public static void main(String[] args) {
for(int i=0; i<5; i++) {
Long startTime = System.currentTimeMillis();
for(int count = 0; count<1000000; count++) {
StudentDto studentDto = new StudentDto();
studentDto.setId(count);
studentDto.setName("Java实体映射工具MapStruct详解");
studentDto.setClassName("清华大学一年级");
studentDto.setCreateTime(new Date());
Student student = new Student();
BeanUtils.copyProperties(studentDto, student);
}
System.out.println("BeanUtils 100w次实体映射耗时:" + (System.currentTimeMillis() - startTime));
startTime = System.currentTimeMillis();
for(int count = 0; count<1000000; count++) {
StudentDto studentDto = new StudentDto();
studentDto.setId(count);
studentDto.setName("Java实体映射工具MapStruct详解");
studentDto.setClassName("清华大学一年级");
studentDto.setCreateTime(new Date());
Student student = StudentMapper.INSTANCE.getModelFromDto(studentDto);
}
System.out.println("MapStruct 100w次实体映射耗时:" + (System.currentTimeMillis()-startTime));
System.out.println();
}
}
}
输出结果如下所示:
BeanUtils 100w次实体映射耗时:548
MapStruct 100w次实体映射耗时:33
BeanUtils 100w次实体映射耗时:231
MapStruct 100w次实体映射耗时:35
BeanUtils 100w次实体映射耗时:227
MapStruct 100w次实体映射耗时:27
BeanUtils 100w次实体映射耗时:219
MapStruct 100w次实体映射耗时:29
BeanUtils 100w次实体映射耗时:218
MapStruct 100w次实体映射耗时:28

从测试结果上可以看出,MapStruct的性能基本上优于BeanUtils一个数量级。

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
2004-10-04 重构(Refactoring)技巧读书笔记 之二