try catch 会降低效率吗? [英] Does try catch decrease efficiency?
问题描述
之间是否存在效率差异:-
Is there an efficiency difference between:-
public boolean canDivisionBeDone(int iA, int iB){
try{
float a = iA/iB;
}catch(Exception e){
return false;
}
return true;
}
和
public boolean canDivisionBeDone(int iA, int iB){
if(iB == 0){
return false;
}else{
float a = iA/iB;
}
return true;
}
如果是,为什么?
推荐答案
从编码的角度来看,我肯定更喜欢条件式 (a == 0 ? 0 : (a/b)
),不是异常处理.这实际上不是异常情况,因此这里不应将异常用于控制流.
From the coding point of view I would definitely prefer a conditional (a == 0 ? 0 : (a/b)
), not exception handling. This is actually not an exceptional situation so exception should not be used for control flow here.
关于效率,我写了一个微基准来测试:
Concerning the efficiency, I wrote a micro-benchmark to test this:
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class MyBenchmark {
private int a = 10;
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;
}
}
}
结果:
Benchmark Mode Cnt Score Error Units
MyBenchmark.conditional avgt 200 7.346 ± 0.326 ns/op
MyBenchmark.exceptional avgt 200 8.166 ± 0.448 ns/op
由于我对 JMH 很陌生,我不确定我的基准测试是否正确.但是从表面上看结果,特殊"方法有点慢(~10%).老实说,我预计会有更大的差异.
As I am quite new to JMH, I am not sure my benchmark is correct. But taking results at the face value, the "exceptional" approach is somewhat (~10%) slower. To be honest, I've expected much greater difference.
这篇关于try catch 会降低效率吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!