Friday, April 21, 2006

Cost of Exception handling

Exception Series Part 2

There are obviously a lot of apparent advantages of using Exception over return error value. However, I wanted to find out the cost of exception handling as compared to return value. So, I wrote a simple Java program and timed the "throughput".


public class Test {
static final int ITER = 10000000;
void func1() throws Exception {
throw new Exception();
}

int func2() {
return 1;
}

public static void main(String[] s) {
Test t = new Test();

// some dumb operation to be done
// in the exc handler and if statement
long someJob1, someJob2;
someJob1 = someJob2 = 0;

// compute the time taken for exceptions
// catch
long start = System.currentTimeMillis();
for (int i = 0; i < ITER; i++) {
try {
t.func1();
}
catch(Exception e) {
// some dumb operation
someJob1++;
}
}
long end = System.currentTimeMillis();
long milli1 = end - start;

// compute time taken for return value
// check
start = System.currentTimeMillis();
for (int i = 0; i < ITER; i++) {
if (t.func2() == 1) {
// some dumb operation
someJob2++;
}
}
end = System.currentTimeMillis();
long milli2 = end - start;

System.out.println("Time spent on exc handling = " + milli1);
System.out.println("Time spent on error checking = " + milli2);
}
};


The outcome on compaq nx7010 laptop running Windows XP Professional on 1 GB RAM using JDK 1.4.2 is -

Time spent on exc handling = 27297
Time spent on error checking = 50


This is amazing. However, one thing to note is that these figures are a bit misleading. Ofcourse exception handling is expensive, but this will not be part of the core path. Remember, the exception is handled in only "exceptional" situations.