i -> i == 1 lambda 基于invokedynamic, 需要初始化时间,初始化后耗时很小。
list.stream()第一次也需要初始化,但是只需要很少时间,差不多2ms。
测试代码:
public static void main(String[] args) {
List numbers1 = Arrays.asList(1, 2, 3);
List numbers2 = Arrays.asList(3, 4);
List numbers3 = new ArrayList<>();
for(int i = 0;i<1000;i++) {
numbers3.add(new Random().nextInt(500));
}
long begin = System.currentTimeMillis();
Collections.sort(numbers1, Comparator.comparing(Integer::intValue));
System.out.println("lambda first_time cost:"+(System.currentTimeMillis()-begin)+"(ms)");
begin = System.currentTimeMillis();
Collections.sort(numbers2, Comparator.comparing(Integer::intValue));
System.out.println("lambda second_time cost:"+(System.currentTimeMillis()-begin)+"(ms)");
for(int i = 0;i<5;i++) {
begin = System.currentTimeMillis();
numbers3.stream().filter(x->x>50).forEach(x->{});
System.out.println("stream "+i+" cost:"+(System.currentTimeMillis()-begin)+"(ms)");
}
}
测试结果:
lambda first_time cost:78(ms)
lambda second_time cost:0(ms)
stream 0 cost:5(ms)
stream 1 cost:1(ms)
stream 2 cost:0(ms)
stream 3 cost:0(ms)
stream 4 cost:0(ms)