java - 在此 Java Stream 用法中是否应该调用映射操作?

标签 java java-8 java-stream

假设这种用法在逻辑上是正确的(即计算所需的 boolean 值):

boolean matches = someObjectList
            .stream()
            .anyMatch(myObjType -> !myObjType.getSomeStatusString().equals("someStatus"));

与以下内容相比如何:

boolean matches = someObjectList
            .stream()
            .map(myObjType -> myObjType.getSomeStatusString())
            .anyMatch(status -> !status.equals("someStatus"));

客观上,一种形式比另一种形式更好吗?字节码有显着差异吗?是一种反模式吗?是否有一些 Java 优化器可以使其中一个比另一个更好?我对基于意见的差异不感兴趣,例如第一个更具可读性,因为这可能因读者而异......

最佳答案

我偶然发现了我正在寻找的答案 in this SO question

所选答案(讨论垃圾收集)部分内容如下:

In implementations like the Hotspot JVM, each thread uses a thread local allocation buffer (TLAB) for new objects. Once its TLAB is full, it will fetch a new one from the allocation space (aka Eden space). If there is none available, a garbage collection will be triggered. Now it’s rather unlikely that all threads hit the end of their TLAB right at the same time. So for the other threads which still have some space in their TLAB left at this time, it would not make any difference if they had allocated some more objects still fitting in that remaining space.

The perhaps surprising conclusion is that not every allocated object has an impact on the garbage collection, i.e. a purely local object allocated by a thread not triggering the next gc, could be entirely free.

我的结论是,第二种方法中“额外”对象的创建没有客观成本。因此,我不认为一种形式相对于另一种形式有任何客观的好处。

关于java - 在此 Java Stream 用法中是否应该调用映射操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59687181/

相关文章:

java - 通过Java okhttp客户端通过HTTPS/SSL连接时出现问题

java - JLayeredPane 中的透明 JPanel

java - EntityClass 中的 LocalDate 扰乱了 sonarQube

java - 如何从另一个类获取调用者方法的注释

lambda - 使用 Java 8 流迭代两个列表

java - Ant 与 JavaMail : authentication required

java - 修剪 Struts2 文本字段字符串输入

java - 扁平化 Java future

java - 从 List<String> 创建 HashMap

Action Streams 中的 Java 8 明确说明