Chapter 6. Exceptions, Casts, and Variables

For every complex problem, there is a solution that is simple, neat, and wrong.

H. L. Mencken


In this section, we examine the cost of exceptions and consider ways to avoid that cost. First, we look at the costs associated with try-catch blocks, which are the structures you need to handle exceptions. Then, we go on to optimizing the use of exceptions.

The Cost of try-catch Blocks Without an Exception

try-catch blocks generally use no extra time if no exception is thrown, although some VMs may impose a slight penalty. The following test determines whether a VM imposes any significant overhead for try-catch blocks when the catch block is not entered. The test runs the same code twice, once with the try-catch entered for every loop iteration and again with just one try-catch wrapping the loop. Because we’re testing the VM and not the compiler, you must ensure that your compiler has not optimized the test away; use an old JDK version to compile it if necessary. To determine that the test has not been optimized away by the compiler, you need to compile the code, then decompile it:

package tuning.exception; public class TryCatchTimeTest { public static void main(String[] args) { int REPEAT = (args.length == 0) ? 10000000 : Integer.parseInt(args[0]); Object[] xyz = {new Integer(3), new Integer(10101), new Integer(67)}; boolean res; long time = System.currentTimeMillis( ); res = try_catch_in_loop(REPEAT, xyz); System.out.println("try catch ...

Get Java Performance Tuning now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.