我应该使用Stream API进行简单的迭代吗? [英] Should I use Stream API for simple iteration?

查看:143
本文介绍了我应该使用Stream API进行简单的迭代吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用新的Stream API进行简单迭代有什么好处吗?

Are there any benefits in using the new Stream API for simple iterations?

没有Stream API:

Without Stream API:

 for (Map.Entry<String, String> entry : map.entrySet()) {
        doSomething(entry);
    }

使用Stream API:

Using Stream API:

map.entrySet().stream().forEach((entry) -> {
        doSomething(entry);
    });

代码的长度和可读性大致相同。是否有任何重要的差异(例如性能)?

Length and readability of code are about the same. Are there any important differences (e.g. in performance)?

推荐答案

Streams API使并行性更容易实现(尽管你会只看到大型收藏的好处)。如果你必须在你的第一个例子上实现并行性,那么代码量会有相当大的差异(而不是将.parallelStream()添加到第二个例子)

The Streams API makes parallelism much easier to accomplish (although you'll only see the benefit with a large sized collection). If you had to implement parallelism on your first example then there would be a sizeable difference in the amount of code (as opposed to adding .parallelStream() to the second example)

根据 Java Trail on parallelism


在使用
集合的应用程序中实现并行性的一个难点是集合不是线程安全的,这意味着
多个线程如果不引入
线程干扰或内存一致性错误,则无法操作集合。 Collections
Framework提供了同步包装器,它将自动
同步添加到任意集合,使其成为线程安全的。
但是,同步会引入线程争用。你想
避免线程争用,因为它阻止线程在
parallel中运行。通过聚合操作和并行流,您可以使用
实现与非线程安全集合的并行性,前提是
在操作时不会修改集合。注意
并行性并不比串行执行
操作更快,尽管如果你有足够的数据和
处理器核心就可以。虽然聚合操作使您能够更轻松地实现并行性,但您仍然有责任确定应用程序是否适合并行化

One difficulty in implementing parallelism in applications that use collections is that collections are not thread-safe, which means that multiple threads cannot manipulate a collection without introducing thread interference or memory consistency errors. The Collections Framework provides synchronization wrappers, which add automatic synchronization to an arbitrary collection, making it thread-safe. However, synchronization introduces thread contention. You want to avoid thread contention because it prevents threads from running in parallel. Aggregate operations and parallel streams enable you to implement parallelism with non-thread-safe collections provided that you do not modify the collection while you are operating on it. Note that parallelism is not automatically faster than performing operations serially, although it can be if you have enough data and processor cores. While aggregate operations enable you to more easily implement parallelism, it is still your responsibility to determine if your application is suitable for parallelism.

这篇关于我应该使用Stream API进行简单的迭代吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆