Java8 parallelStream与迭代器Iterator性能
2024-10-15 06:33:23
定义一个测试类
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.csdn.net/u011001723/article/details/52794455/
最新文章
- 转发 eclipse 取消javascript 验证
- 【转】Velocity 语法
- Simulating a Freight robot in Gazebo
- C类型
- java之classpath到底是什么
- cocos2dx3.4 解析json文件
- TCP/UDP客户端
- bat检测文件大小并邮件报警
- App上架应用市场,如何攻破安全过检难题
- 四则运算4(Android版)
- ES6躬行记(20)——类
- (转)ArcGIS Runtime for Android 使用异步GP服务绘制等值线
- initWithFrame方法的使用
- (转)面向对象(深入)|python描述器详解
- .19-浅析webpack源码之compile流程-rules参数处理(2)
- elasticsearch安装ik分词器(非极速版)
- JDK1.10+scala环境的搭建之windows环境
- Memcpy, blockcopy的进一步理解
- redis——持久化方式RDB与AOF分析
- IO相关2(文件输入输出)