Inspired by another question on Stack Overflow, I have written a micro-benchmark to check, what is more efficient:
- conditionally checking for zero divisor or
- catching and handling an
ArithmeticException
Below is my code:
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class MyBenchmark {
private int a = 10;
// a little bit less obvious than int b = 0;
private int b = (int) Math.floor(Math.random());
@Benchmark
public float conditional() {
if (b == 0) {
return 0;
} else {
return a / b;
}
}
@Benchmark
public float exceptional() {
try {
return a / b;
} catch (ArithmeticException aex) {
return 0;
}
}
}
I am totally new to JMH and not sure if the code is allright.
Is my benchmark correct? Do you see any mistakes?
Side not: please don't suggest asking on https://codereview.stackexchange.com. For Codereview code must already work as intended. I am not sure this benchmark works as intended.