几款常用的Bean拷贝工具类性能测试

测试代码

@Test
void test() {
	// 获取原始数据
    HgPatient patient = patientService.getById(1);
    // 创建测试秒表
    StopWatch sw = StopWatch.create("性能测试秒表");
    // 循环拷贝10000次
    int count = 10000;

    sw.start("Spring#copyProperties");
    for (int i = 0; i < count; i++) {
        PatientVo vo = new PatientVo();
        BeanUtils.copyProperties(patient, vo);
    }
    sw.stop();

    sw.start("Hutool#copyProperties");
    for (int i = 0; i < count; i++) {
        PatientVo vo = new PatientVo();
        BeanUtil.copyProperties(patient, vo, CopyOptions.create().ignoreNullValue());
    }
    sw.stop();

    sw.start("Hutool#toBean");
    for (int i = 0; i < count; i++) {
        PatientVo vo = BeanUtil.toBean(patient, PatientVo.class, CopyOptions.create().ignoreNullValue());
    }
    sw.stop();

    sw.start("CglibUtil#copy");
    for (int i = 0; i < count; i++) {
        PatientVo vo = CglibUtil.copy(patient, PatientVo.class);
    }
    sw.stop();

    System.out.println(sw.prettyPrint(TimeUnit.MILLISECONDS));
}

测试结果

StopWatch '性能测试秒表': running time = 1298 ms
---------------------------------------------
ms         %     Task name
---------------------------------------------
000000354  27%   Spring#copyProperties
000000548  42%   Hutool#copyProperties
000000286  22%   Hutool#toBean
000000108  08%   CglibUtil#copy

花费时间比较

  • 数据量 < 1000:Spring#copyPropertiesHutool#toBeanCglibUtil#copy < Hutool#copyProperties
  • 1000 < 数据量 < 10000:CglibUtil#copy < Spring#copyPropertiesHutool#toBean < Hutool#copyProperties
  • 数据量 > 10000:CglibUtil#copy << Spring#copyProperties < Hutool#toBean < Hutool#copyPropertiesCglib快如闪电】

使用推荐

数据量大的情况下毫无疑问选用Cglib,日常使用的话推荐用Hutool#toBean,一行代码即可将数据库实体拷贝为VODTO,且支持自定义,例如是否拷贝空值等。Apache#copyProperties性能过差,完全不推荐使用。

你可能感兴趣的:(常用工具类,java)