測試代碼
@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 循環(huán)消耗時間="+(endTime-startTime));
startTime = System.currentTimeMillis();
lambdaList = originList.stream().filter(i->i.intValue()%2==0).collect(Collectors.toList());
endTime = System.currentTimeMillis();
System.out.println("lambda 循環(huán)消耗時間="+(endTime-startTime));
}
測試結(jié)果
initialCapacity = 100000
for 循環(huán)消耗時間=3
lambda 循環(huán)消耗時間=90
initialCapacity = 1000000
for 循環(huán)消耗時間=12
lambda 循環(huán)消耗時間=127
initialCapacity = 10000000
for 循環(huán)消耗時間=45
lambda 循環(huán)消耗時間=281