有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在此Java流使用中是否应该调用映射操作?

假设此用法在逻辑上(即,它计算所需的布尔值)正确:

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

与此相比:

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

一种形式客观上比另一种好吗?字节码之间有显著差异吗?一个是反模式吗?是否有一些Java优化器使一个比另一个更好?我对基于观点的差异不感兴趣,比如第一种更具可读性,因为不同的读者可能会有所不同


共 (1) 个答案

  1. # 1 楼答案

    我偶然发现了我想要的答案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.

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