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

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

问题描述

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

没有 Stream API:

 for (Map.Entry entry : map.entrySet()) {做某事(条目);}

使用流 API:

map.entrySet().stream().forEach((entry) -> {做某事(条目);});

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

解决方案

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

根据 Java Trail on parallelism:p><块引用>

在应用程序中实现并行性的一个困难是使用collections 是集合不是线程安全的,这意味着多个线程不能在不引入的情况下操作集合线程干扰或内存一致性错误.收藏品框架提供了同步包装器,它添加了自动同步到任意集合,使其成为线程安全的.但是,同步会引入线程争用.你想要避免线程争用,因为它会阻止线程运行平行线.聚合操作和并行流使您能够使用非线程安全集合实现并行性,前提是操作时不要修改集合.笔记并行性不会自动比执行更快串行操作,尽管如果您有足够的数据和处理器内核.虽然聚合操作使您能够更轻松地实现并行性,您仍然有责任确定是否您的应用程序适合并行性.

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

Without Stream API:

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

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)?

解决方案

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)

As per the Java Trail on parallelism:

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天全站免登陆