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一個數量級。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章