1.for循环
for循环的性能随着数据量的增加性能也越来越差。
2.stream(串行流)
stream在数据量小的情况下性能差(小于100),在数据量中、大的时候性能略高于for循环(100-10W),但当数据量特别大的时候(10W+),性能也变得越来越差。
3.parallelStream(并行流)
parallelStream适用的场景是CPU密集型的,加入电脑本身CPU负载很大,parallelStream并不能起到并行流的作用。
parallelStream无法保证元素的顺序,多线程情况下,会有线程安全问题。
parallelStream在数据量小的情况下性能略高于串行化流,略低于for循环(小于100)。在数据量中、大的时候情况都差不多(100-10W),但是当数据量特别大(100W+)的时候,性能也变得更好。
public class MainTest {
public static void main(String[] args) {
List<Integer> integerList = Lists.newArrayList(1,2,3,4,5,6);
integerList.stream().forEach(data->System.out.println(Thread.currentThread().getName() +":"+ data));
/*
stream 串行流==线程安全 ==有序
main:1
main:2
main:3
main:4
main:5
main:6
*/
System.out.println("----------------我是分割线--------------------");
integerList.parallelStream().forEach(data->System.out.println(Thread.currentThread().getName() +":"+ data));
/*
适用单纯的数据处理
parallelStream 并行流==线程不安全==无序==效率高(抢占CPU资源)
通过设置虚拟机启动参数配置woker的数量
-Djava.util.concurrent.ForkJoinPool.common.parallelism=N
main:4
main:6
main:5
ForkJoinPool.commonPool-worker-1:2
ForkJoinPool.commonPool-worker-1:3
ForkJoinPool.commonPool-worker-1:1
*/
}
}
4.总结
工作中一般考虑到效率时使用for循环即可【小集合】。考虑到方便场景使用stream即可。考虑的超大数据量处理是考虑使用parallelStream。