Does the order of if else matter for performance? e.g. put the most likely condition in the front is better

Viewed 135

I'm trying to measure if the order of if else affects performance.

For example, if

if (condition == more likely condition) {}
else /** condition == rare condition **/ {}

is faster than

if (condition == rare condition) {}
else /** condition == more likely condition **/ {}

I think maybe JIT should be able to optimise it no matter which order I put it? Couldn't find any documentation on this though.

I tried to test it out myself with following benchmark. Based on it, I don't see strong evidence that the order matters. Because if it does, I think the throughput when bias=0.9 (probability of if (zeroOrOne == 1) is true is 0.9) should be higher than when bias=0.1 (else probability is 0.9).

public class BranchBench {
    @Param({ "0.02", "0.1", "0.9", "0.98", })
    private double bias;

    @Param("10000")
    private int count;

    private final List<Byte> randomZeroOnes = new ArrayList<>(count);

    @Setup
    public void setup() {
        Random r = new Random(12345);

        for (int c = 0; c < count; c++) {
            byte zeroOrOne = (byte) (c < (bias * count) ? 1 : 0);
            randomZeroOnes.add(zeroOrOne);
        }
        Collections.shuffle(randomZeroOnes, r);
    }

    @Benchmark
    public int static_ID_ifElse() {
        int i = 0;
        for (final Byte zeroOrOne : randomZeroOnes) {
            if (zeroOrOne == 1) {
                i++;
            } else {
                i--;
            }
        }
        return i;
    }
}
Benchmark                     (bias)  (count)   Mode  Cnt    Score   Error   Units
BranchBench.static_ID_ifElse    0.02    10000  thrpt   15  137.409 ± 1.376  ops/ms
BranchBench.static_ID_ifElse     0.1    10000  thrpt   15  129.277 ± 1.552  ops/ms
BranchBench.static_ID_ifElse     0.9    10000  thrpt   15  125.640 ± 5.858  ops/ms
BranchBench.static_ID_ifElse    0.98    10000  thrpt   15  137.427 ± 2.396  ops/ms
1 Answers

On modern processors I don't think the order of your conditionals really matter that much anymore. As part of the instruction pipeline, processors will do what is called branch prediction; where it guesses which condition will be true and pre-loads the instructions into the pipeline.

These days, processors guess correctly >90% of the time, so any hand-written conditional tweaking is less important.

There are quite a lot of literature on branch prediction:

https://dzone.com/articles/branch-prediction-in-java

https://www.baeldung.com/java-branch-prediction

Related