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

前端 未结 5 1185
旧时难觅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:59

    I will add my 0.02$ here.

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

    Branch Prediction is a CPU feature, it has nothing to do with JVM. It is needed to keep CPU pipeline full and ready to do something. Measuring or predicting the branch prediction is extremely hard (unless you actually know the EXACT things that the CPU will do). This will depend on at least the load that the CPU is having right now (that might be a lot more than your program only).

    However the performance with Streams is always turning out to be worse than traditional loops

    This statement and the previous one are un-related. Yes, streams will be slower for simple examples like yours, up to 30% slower, which is OK. You could measure for a particular case how slower they are or faster via JMH as others have suggested, but that proves only that case, only that load.

    At the same time you might be working with Spring/Hibernate/Services, etc etc that do things in milliseconds and your streams in nano-seconds and you worry about the performance? You are questioning the speed of your fastest part of the code? That's of course a theoretical thing.

    And about your last point that you tried with sorted and un-sorted arrays and it gives you bad results. This is absolutely no indication of branch prediction or not - you have no idea at which point the prediction happened and if it did unless you can look inside the actual CPU pipelines - which you did not.

提交回复
热议问题