本文透過一個簡單的示例程式碼,比較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一個數量級。
