When should streams be preferred over traditional loops for best performance? Do streams take advantage of branch-prediction?

前端 未结 5 1163
旧时难觅i
旧时难觅i 2020-12-13 17:05

I just read about Branch-Prediction and wanted to try how this works with Java 8 Streams.

However the performance with Streams is always turning out to be wors

5条回答
  •  失恋的感觉
    2020-12-13 17:49

    How can my Java program run fast?

    Long story short, Java programs can be accelerated by:

    1. Multithreading
    2. JIT

    Do streams relate to Java program speedup?

    Yes!

    1. Note Collection.parallelStream() and Stream.parallel() methods for multithreading
    2. One can write for cycle that is long enough for JIT to skip. Lambdas are typically small and can be compiled by JIT => there's possibility to gain performance

    What is the scenario stream can be faster than for loop?

    Let's take a look at jdk/src/share/vm/runtime/globals.hpp

    develop(intx, HugeMethodLimit,  8000,
            "Don't compile methods larger than this if "
            "+DontCompileHugeMethods")
    

    If you have long enough cycle, it won't be compiled by JIT and will run slowly. If you rewrite such a cycle to stream you'll probably use map, filter, flatMap methods that split code to pieces and every piece can be small enough to fit under limit. For sure, writing huge methods has other downsides apart from JIT compilation. This scenario can be considered if, for example, you've got a lot of generated code.

    What's about branch prediction?

    Of course streams take advantage of branch prediction as every other code does. However branch prediction isn't the technology explicitly used to make streams faster AFAIK.

    So, when do I rewrite my loops to streams to achieve the best performance?

    Never.

    Premature optimization is the root of all evil ©Donald Knuth

    Try to optimize algorithm instead. Streams are the interface for functional-like programming, not a tool to speedup loops.

提交回复
热议问题