Chapter 6. Exceptions, Assertions, Casts, and Variables

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

H. L. Mencken

This chapter describes the costs of various programmatic elements, including exceptions, assertions (new in 1.4), casts, and variables. It also describes how to optimize your use of these elements.

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.

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]); ...

Get Java Performance Tuning, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.