Performance of Exception Handling, Part 2

18 November 2003

I decided to test just how much of a performance hit we incur by just handling the exceptions instead of avoiding them. It's worse than I expected.

Here's the code:

public class ExceptionTest {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        for (int i = 0; i < 1000000; i ++) {
            Object x = null;
            String y = "y";
            try {
                y = x.toString();
            } catch (NullPointerException ignored) { }
        }
        System.out.println(System.currentTimeMillis() - start);

        start = System.currentTimeMillis();
        for (int i = 0; i < 1000000; i ++) {
            Object x = null;
            String y = "y";
            if (x != null) {
                y = x.toString();
            }
        }
        System.out.println(System.currentTimeMillis() - start);
    }
}

And the results:

92037
20

Unbelievable! It makes sense though, since the one that used exceptions needed to create 1 million NullPointerException objects, and the other created no objects. This loop amplifies the affect, so maybe it's still not so bad if you're just doing it once through. I think personally, I'm going to start checking nulls again.


Filed Under: