因为接手的项目中含有一些beanUtil类,业务代码中也不乏一些使用,但是用的工具不统一,出于好奇,我写了个小demo测试一下这些工具类的性能,这里主要挑了两个代表。
一个是:org.springframework.beans.BeanUtils
另一个是:cn.hutool.core.bean
下面贴出我的测试方法:
private void timePrint(Runnable... runnable){
IntStream.range(0,runnable.length).forEach(index->{
long l = System.currentTimeMillis();
runnable[index].run();
System.out.println("Array"+index+":"+(System.currentTimeMillis()-l));
});
}
private void fore(int forCount, Consumer<Integer> consumer){
IntStream.range(0,forCount).forEach(consumer::accept);
}
尽管不太精确,但是也可以看出个大概(忽略jit等等其他因素的影响)
1.首先看看创建对象的性能对比,这里以创建10000个对象为例子,通过无参构造创建对比。
@Test
public void T9(){
int forCount = 10000;
timePrint(()->{
//直接反射构造
Constructor<ExcelDTOStudent> constructor;
try {
constructor = ExcelDTOStudent.class.getConstructor();
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
fore(forCount,index->{
try {
constructor.newInstance();
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
});
},()-> fore(forCount,index->{
//反射
try {
ExcelDTOStudent.class.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}
//hu-tool
}),()->fore(forCount,index-> ReflectUtil.newInstanceIfPossible(ExcelDTOStudent.class))
//直接 new
,()->fore(forCount,index->new ExcelDTOStudent())
//spring
,()->fore(forCount,index->BeanUtils.instantiateClass(ExcelDTOStudent.class)));
}
各位不妨猜测一下结果,最快的当然毫无疑问是直接new创建的。
额,还是公布结果吧,跑了很多次,但是每次结果都差不多。各个方式之间差距是悬殊