Make sure, you benchmark correctly

Recently, I read posts about some Java loop benchmarks. I am not entirely sure, if the outcome and advise given is correct, so here is my version. I don’t want to blame any of the other tests for being incorrect, but judge for yourself.

Spoiler alert: The type of loop might or might not make a difference and overall, it is rather not the loop that makes the difference but all the other code that leads to conditions that might make some loops run faster, despite the same work/task. And yes, parallelStream() is mostly a bad idea.

This article also will give you a brief glimpse into benchmarking as well as teach you, that most benchmarks are wrong or better, the benchmark is right but the conclusions are wrong. Bring some time, the article got longer than expected. The article is not going to teach you how to benchmark with JMH, how the JVM works, or how that all is executed by the CPU. It might just overwhelm you with facts. But hey, it is not supposed to be the last article on that subject.

Continue reading