gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 18:54:36 24 4
gpt4 key购买 nike

假设这种用法在逻辑上是正确的(即计算所需的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com