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

前端 未结 5 1187
旧时难觅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 18:03

    Java is a high level language saving the programmer from considering low level performance optimization.

    Never choose a certain approach for performance reasons unless you have proven that this is a problem in your real application.

    Your measurements show some negative effect for streams, but the difference is below observability. Therefore, it's not a Problem. Also, this Test is a "synthetic" situation and the code may behave completely different in a heavy duty production environment. Furthermore, the machine code created from your Java (byte) code by the JIT may change in future Java (maintenance) releases and make your measurements obsolete.

    In conclusion: Choose the syntax or approach that most expresses your (the programmer's) intention. Keep to that same approach or syntax throughout the program unless you have a good reason to change.

提交回复
热议问题