简体   繁体   中英

Should map operation be invoked in this Java Stream usage?

Assuming that this usage is logically (ie it calculates the desired boolean value) correct:

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

how would that compare to:

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

Is one form objectively better than the other? Is there a significant difference in the bytecode? Is one an anti-pattern? Is there some Java Optimizer that makes one better than the other? I am not interested in opinion based differences such as the first is more readable, as that may differ from reader to reader....

I stumbled across the answer I was looking for in this SO question

The selected answer (discussing Garbage Collection) says in part:

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 , ie a purely local object allocated by a thread not triggering the next gc, could be entirely free.

My conclusion is that the creation of the "extra" objects in the second approach comes at no objective cost. Thus I do not believe there to be any objective benefit of one form over the other.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM