在这篇文章中,我们将看一个简单的例子,捕捉异常是如何影响性能的。
private static void exceptionTest(){
int i=0;
int j=1;
try{
int k=j/i;
}catch(ArithmeticException ex){
//not good idea to catch run time exception but catch for demo only
}
}
private static void withoutExceptionTest(){
int i=0;
int j=1;
if(i>0){
int k=j/i;
}
}
private static long exceptionTestLoop(int iterations,boolean isCatchException){
long startTime=System.nanoTime();
for(int i=0;i<iterations;i++){
if(isCatchException){
exceptionTest();
}else{
withoutExceptionTest();
}
}
long endTime=System.nanoTime();
long time=endTime-startTime;
return time;
}
public static void main(String[] args) {
int itr=1000000;
long timeForCatching=exceptionTestLoop(itr,true);
long time=exceptionTestLoop(itr,false);
System.out.println("Time for catching Exception "+timeForCatching+" without catching "+time);
}
避免捕捉异常,因为这会缩短响应时间。上面的例子展示了一个简单的单线程应用程序的结果;然而,在多线程环境中,情况将变得更糟。