测试代码
@Test
public void test(){
int initialCapacity = 10000000;
List<Integer> originList = new ArrayList<>(initialCapacity);
List<Integer> forList = new ArrayList<>(initialCapacity/2);
List<Integer> lambdaList = new ArrayList<>(initialCapacity/2);
for (int i = 0; i < initialCapacity; i++) {
originList.add(i);
}
Long startTime = System.currentTimeMillis();
for(Integer i : originList){
if(i.intValue()%2==0){
forList.add(i);
}
}
Long endTime = System.currentTimeMillis();
System.out.println("for 循环消耗时间="+(endTime-startTime));
startTime = System.currentTimeMillis();
lambdaList = originList.stream().filter(i->i.intValue()%2==0).collect(Collectors.toList());
endTime = System.currentTimeMillis();
System.out.println("lambda 循环消耗时间="+(endTime-startTime));
}
测试结果
initialCapacity = 100000
for 循环消耗时间=3
lambda 循环消耗时间=90
initialCapacity = 1000000
for 循环消耗时间=12
lambda 循环消耗时间=127
initialCapacity = 10000000
for 循环消耗时间=45
lambda 循环消耗时间=281
网友评论