Java8 parallelStream与迭代器Iterator性能

时间:2025-04-20 10:05:37

定义一个测试类

public class TestParallelStream {

    private List<Integer> list;
private int size;
private CountDownLatch countDownLatch;
@Before
public void initList(){
list = new ArrayList<>();
size = 100;
countDownLatch = new CountDownLatch(size);
for(int i=0; i<size; i++) {
list.add(i);
}
}

上面定义了一个100元素的list。

下面使用迭代器遍历:

/**
* 迭代器遍历
* @throws Exception
*/
@Test
public void testFor() throws Exception {
long start = System.currentTimeMillis();
Iterator<Integer> iterator = list.iterator();
while(iterator.hasNext()){
System.out.print(iterator.next());
}
System.out.println(); long end = System.currentTimeMillis(); System.out.println(end-start);
}

结果耗时稳定一位数的毫秒

使用parallelStream的方式:

/**
* 使用parallelSteam.forEach()遍历
* @throws Exception
*/
@Test
public void testListForEach() throws Exception{
long start = System.currentTimeMillis();
list.parallelStream().forEach(
l -> {
System.out.print(l); countDownLatch.countDown();
}
);
countDownLatch.await();
System.out.println(); long end = System.currentTimeMillis(); System.out.println(end-start);
}

结果是稳定在50以上的两位数的毫秒。

但是当我们要进行耗时的操作时,比如说IO,这里用Thread.sleep(100)模拟IO。

用迭代器处理模拟的IO的方式:

/**
* 当有耗时操作时,使用迭代器遍历
* @throws Exception
*/
@Test
public void testForSleep() throws Exception {
long start = System.currentTimeMillis();
Iterator<Integer> iterator = list.iterator();
while(iterator.hasNext()){
System.out.print(iterator.next());
Thread.sleep();
}
System.out.println(); long end = System.currentTimeMillis(); System.out.println(end-start);
}

结果是比大一些的毫秒数。

用parallelStream处理模拟的IO:

/**
* 当有耗时操作时,使用parallelSteam.forEach()遍历
* @throws Exception
*/
@Test
public void testListParallelStream() throws Exception{
long start = System.currentTimeMillis();
list.parallelStream().forEach(
l -> {
System.out.print(l);
try {
Thread.sleep();
} catch (InterruptedException e) {
e.printStackTrace();
}
countDownLatch.countDown();
}
);
countDownLatch.await();
System.out.println(); long end = System.currentTimeMillis(); System.out.println(end-start);
}

结果是比大一些的毫秒数。应该是跟我电脑4核有关,处理4个线程。是上面迭代器遍历时间的1/4.

总结

当数据量不大或者没有太耗时的操作时,顺序执行(如iterator)往往比并行执行更快,毕竟,分配资源、准备线程池和其它相关资源也是需要时间的;

当任务涉及到耗时操作(如I/O)并且任务之间不互相依赖时,那么并行化就是一个不错的选择。通常而言,将这类程序并行化之后,执行速度会提升好几个等级;

由于在并行环境中任务的执行顺序是不确定的,因此对于依赖于顺序的任务而言,并行化也许不能给出正确的结果。

参考:

https://blog.****.net/u011001723/article/details/52794455/