The Cost of try-catch Blocks Without an Exception

- 135 - Generally, you cannot expect to support internationalized strings and retain the performance of simple one-byte-per-character strings. But, as shown here, you can certainly improve the performance by some useful amounts.

6.1 Exceptions

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.

6.1.1 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 were 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 mainString[] args { int REPEAT = args.length == 0 ? 10000000 : Integer.parseIntargs[0]; Object[] xyz = {new Integer3, new Integer10101, new Integer67}; boolean res; long time = System.currentTimeMillis ; res = try_catch_in_loopREPEAT, xyz; System.out.printlntry catch in loop took + System.currentTimeMillis - time; time = System.currentTimeMillis ; res = try_catch_not_in_loopREPEAT, xyz; System.out.printlntry catch not in loop took + System.currentTimeMillis - time; Repeat the two tests several more times in this method for consistency checking ... } public static boolean try_catch_not_in_loopint repeat, Object[] o { Integer i[] = new Integer[3]; try { for int j = repeat; j 0; j-- { i[0] = Integer o[j+12]; i[1] = Integer o[j2]; i[2] = Integer o[j+22]; } return false; } catch Exception e {return true;} } - 136 - public static boolean try_catch_in_loopint repeat, Object[] o { Integer i[] = new Integer[3]; for int j = repeat; j 0; j-- { try { i[0] = Integer o[j+12]; i[1] = Integer o[j2]; i[2] = Integer o[j+22]; } catch Exception e {return true;} } return false; } } Running this test in various VMs results in a 10 increase in the time taken by the looped try- catch test relative to the nonlooped test for some VMs. See Table 6-1 . Table 6-1, Extra Cost of the Looped try-catch Test Relative to the Nonlooped try-catch Test VM 1.2 1.2 no JIT 1.3 HotSpot

1.0 1.1.6

Increase in time ~10 None ~10 ~10 None

6.1.2 The Cost of try-catch Blocks with an Exception