Performance of Exception Handling

I hate checking nulls in my code. It seems so blatantly inefficient -- blindly checking if x != null before I do anything with it. Those are wasted CPU cycles!

I like to do this instead:

String x = "default";
try {
    x = request.getParameter("x").toString();
} catch (NullPointerException ignored) { }

According to this article, though, my way could be even more grossly inefficient than testing nulls all the time.

It seems that while I'm saving time not checking null all the time, in the cases where it is null, it takes especially long to snapshot the system, produce the Exception stack trace, and throw it. try-catch blocks don't really take extra time, it's the creation of an Exception when I let them happen which cause the performance hit.

This is quite disappointing, as I always thought my way was a slick enhancement, but it makes perfect sense that it is not. I expect I'll find a balance somewhere in between my wasteful use of exception handling and implementing fanatical null checks around every corner.

Filed Under: Java