Performance Tip :- Avoid Catching Exceptions

Introduction

In this post we will look at simple example how does catching exception impact performance.

Code Sample

Code for catching exception

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
 }
 }

Code where conditions are handled

private static void withoutExceptionTest(){
 int i=0;
 int j=1;
 if(i>0){
 int k=j/i;
 }
 }

method to call logic

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;
 }

main method

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);
 }

Results

exception_catch

Conclusion

Avoid catching exception as it will reduce response time. above example demonstrate results for simple single threaded application but situation become worst in multi threaded environment.

%d bloggers like this: