我试图衡量if else
的顺序是否会影响性能.
例如,如果
if (condition == more likely condition) {}
else /** condition == rare condition **/ {}
快于
if (condition == rare condition) {}
else /** condition == more likely condition **/ {}
我认为,也许JIT应该能够优化它,无论我把它的顺序?但找不到任何有关此的文档.
我试着用以下基准测试自己.基于这一点,我没有看到强有力的证据表明顺序很重要.因为如果是这样,我认为当bias=0.9
(if (zeroOrOne == 1)
的概率为真是0.9)时的吞吐量应该高于当bias=0.1
(else
的概率为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